nodejs中for循環和異步調用的那些坑

在nodejs中for循環中是不能嵌套使用異步調用的,就像下面的:

我們定義一個post請求,用於接受前端發送來的文件,然後使用for循環對目錄下的一些文件依次做一些異步調用事情(使用fs的stat)

router.post('/uploadfile', function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            return res.end("Error uploading file.");
        }
        for(let i = 0; i<req.files.length;i++) {
            fs.stat('./', req.files[i].originalname, function (err, stats) {
                //do somethins
                console.log(i);
            })
        }
        res.end("File is uploaded");
    });
});

這裏我們期望打印的log是從1到file文件的數量-1,可結果不會如我們所想,因爲是異步調用,for循環不會按照要求執行,改進方式是使用遞歸調用
router.post('/uploadfile', function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            return res.end("Error uploading file.");
        }
        (function iterator(index) {
            if(index === req.files.length) {
                return;
            }
            fs.stat('./', req.files[index].originalname,function (err, stats) {
                // do something
                console.log(index);
                iterator(index + 1);
            })
        })
        res.end("File is uploaded");
    });
});


以上內容經過真實校驗,詳見:https://github.com/webPageDev/Demo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章