Javascript foreach中的承诺
我有一些关于逻辑的代码 我下面的代码块按预期工作,因此Javascript foreach中的承诺,javascript,node.js,foreach,promise,Javascript,Node.js,Foreach,Promise,我有一些关于逻辑的代码 我下面的代码块按预期工作,因此将被更新变量无法以同步方式进行逐字更新 var willbeUpdated = 1; anArray.forEach(function(i){ getPromisedData(i).then(function(d){ willbeUpdated += d; }); }); if (wiillbeUpdated == something) { // some logic } 所以问题是,我是否必须为foreac
将被更新
变量无法以同步方式进行逐字更新
var willbeUpdated = 1;
anArray.forEach(function(i){
getPromisedData(i).then(function(d){
willbeUpdated += d;
});
});
if (wiillbeUpdated == something) {
// some logic
}
所以问题是,我是否必须为foreach逻辑再次创建另一个承诺的方法,并将置于if logic
的then方法之外,这将是一个最佳实践,或者在这种情况下有任何其他更好的想法
编辑:我问这个问题是想听听关于嵌套异步函数处理的最好或更好的方法,而不是确切的代码块,谢谢。我想你要找的是把if块(
willBeUpdated==something
)放在getPromisedData
解析的函数中
因此:
会有结果的。如果你能让我更好地了解你想做什么,那么可能会有更好的解决方案。我想你要找的是把If块(
willBeUpdated==某物
)放在getPromisedData
解析的函数中
因此:
会有结果的。如果您能让我更好地了解您正在尝试做什么,那么可能会有更好的解决方案。
q
和许多其他promise库可以处理promise数组,并等待结果
var q = require('q');
var willbeUpdated = 1;
var todo = [];
anArray.forEach(function(i){
todo.push(getPromisedData(i).then(function(d) {
return (willbeUpdated+= d);
}));
});
q(todo).then(function() {
if (wiillbeUpdated == something) {
// some logic
}
});
q
和许多其他promise库可以处理promise数组,并等待结果
var q = require('q');
var willbeUpdated = 1;
var todo = [];
anArray.forEach(function(i){
todo.push(getPromisedData(i).then(function(d) {
return (willbeUpdated+= d);
}));
});
q(todo).then(function() {
if (wiillbeUpdated == something) {
// some logic
}
});
使用
使用
在简单递增的情况下,它可以工作,但不会等待所有任务结束,并且会在完成任务之前做一些事情。这样,if逻辑将作为数组长度计数运行。在简单递增的情况下,它可以工作,但不会等待所有任务结束,并会在完成任务之前执行某些操作。这样,if逻辑将以数组长度计数的形式运行。您和@Gothdo的答案似乎没有问题,但问题不在于代码是否完全正确,例如,在嵌套循环中,返回值以获取其最新值将非常困难,这个解决方案是唯一的方法吗?你和@Gothdo的答案似乎还可以,但问题不完全在于代码,例如,在嵌套循环中,将返回值推到其最新值是非常困难的,这个解决方案是唯一的方法吗?
var willbeUpdated = 1,
promises = [];
anArray.forEach(function(i){
promises.push(getPromisedData(i));
});
Promise.all(promises).then(function() {
// some logic
});