[英]Promise with two for loops nested Javascript
I would like to create an asynchronous method with promise but I can't understand why it doesn't worked with my program below :我想用 promise 创建一个异步方法,但我不明白为什么它不能与我的程序一起使用:
app.get('/historique', function (req, res) {
const pathFolders = `.\\..\\website\\src\\assets\\covering\\`;
const promise2 = new Promise(function (resolve, reject) {
fs.readdirSync(pathFolders).forEach(folder => {
recursive(`${pathFolders}\\${folder}\\`, function (err, files) {
var datapath = [];
files.forEach(file => {
console.log("1");
});
console.log("2");
});
console.log("3");
resolve("3");
});
});
promise2.then(function (value) {
console.log("end")
res.status(200).send("end")
});
})
Normally, I would like the program to show in the order on the console.log 1 1 1 2 1 1 2 ... then 3 and finally "end".通常,我希望程序在 console.log 上按顺序显示 1 1 1 2 1 1 2 ... 然后是 3,最后是“结束”。 But the console.log show me first 3 then "end" then 1 1 1 2 1 1 2 ...但是 console.log 先显示 3 然后“end”然后是 1 1 1 2 1 1 2 ...
Can you help me please.你能帮我吗。 I think this is because of the for loop but I can't solve this problem.我认为这是因为 for 循环,但我无法解决这个问题。
As E. Zacarias already explained in his comment, the recursive-readdir
implementation is implemented asynchronously.正如 E. Zacarias 在他的评论中已经解释的那样, recursive-readdir
实现是异步实现的。 But it supports being used with a Promise
by leaving out the callback argument.但是它通过省略回调参数支持与Promise
一起使用。
Then you can return a Promise
from the iterator function and wait for it with Promise.all
.然后你可以从迭代器函数返回一个Promise
并用Promise.all
等待它。
This will make your code much more straightforward:这将使您的代码更加简单:
app.get('/historique', function (req, res) {
const pathFolders = `.\\..\\website\\src\\assets\\covering\\`;
const promise2 = Promise.all(
// readdirSync returns an Array of folder name strings
// Call Array.map to transform it into an array of Promise
fs.readdirSync(pathFolders).map(folder => {
// return a Promise for the folder from the map function
return recursive(`${pathFolders}\\${folder}\\`).then(files => {
var datapath = [];
files.forEach(file => {
console.log("1");
});
console.log("2");
});
});
);
promise2.then( value => {
console.log("end")
res.status(200).send("end")
});
})
The important aspects here are to understand the workings of Array.prototype.map and Promise.all .这里的重要方面是了解Array.prototype.map和Promise.all的工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.