在nodejs中for循環中是不能嵌套使用異步調用的,就像下面的:
我們定義一個post請求,用於接受前端發送來的文件,然後使用for循環對目錄下的一些文件依次做一些異步調用事情(使用fs的stat)
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
}
res.end("File is uploaded");
});
});
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");
});
});