我使用promises执行下面的代码。我遇到的问题是,在继续执行下一个块之前等待第一个块执行顺序不是顺序执行
下面是代码:
array[]
new Promise(function(resolve, reject) {
//userarray is some array with user id's
userarray.forEach(function(entry) {
User.findOne({ user_id: entry}, function(err, user) {
if (err) throw err;
console.log(user.name);
array.push(user.name);
});
});
resolve("success");
})
.then(function() {
console.log(array);
console.log("done");
});
以下是输出
[] //数组仍为空
完成
汤姆
迪克
哈里
当我想要的是
汤姆
迪克
哈里
[“tom”,“dick”,“harry”]
完成
答案 0 :(得分:4)
似乎User.findOne
将异步调用其回调,以便在实际调用回调之前解析您的promise。你可以尝试这样的事情:
var promises = userarray.map(function(entry) {
return new Promise(function(resolve, reject) {
User.findOne({ user_id: entry}, function(err, user) {
if (err) reject(err);
console.log(user.name);
resolve(user.name);
});
});
});
Promise.all(promises).then(function(array) {
console.log(array);
console.log("done");
});
答案 1 :(得分:0)
这个解决方案不是很优雅,但应该完成工作。
Copy-Item -path $sourceDir\*.txt -Destination $destDir