使得异步在一个循环中的JavaScript任务 [英] Making async javascript task in a loop
问题描述
function(obj){
for (property in obj) {
if (obj.hasOwnProperty(property)) {
// some code here
if(condition){
obj.children = example.getdata(base, obj.name);
}
// some more code releated to obj
}
}
if (obj.length == 10)
{
//some more function
}
}
现在我想要的 example.getdata STRONG>异步,但我不希望执行如果语句中的循环,直到所有的同步之后任务都做了。
它更多的像我希望所有的 example.getdata STRONG>函数调用来并行执行和他们完成工作后,我执行,如果(obj.length)。
Now i want to make example.getdata async but i dont want to execute if statement that is after for loop until all the sync tasks are done. Its more of like i want all the example.getdata function calls to execute in parallel and after they finish work i execute if (obj.length).
我尝试使用的承诺,推动所有承诺并加以解决,但我不知道如何来处理每个函数调用的返回值。
I tried using promises and push all the promises and resolve them but i dont know how to handle the return value for each function call.
推荐答案
下面是一个使用循环许诺干净的例子。如果你能挑一个承诺库库像蓝鸟将使它更简单:
Here is a clean example of a for loop using promises. If you can pick a promise library libraries like Bluebird will make it even simpler:
function(obj){
var props = Object.keys(obj), p = Promise.resolve();
props.forEach(function(prop){
p = p.then(function(){
if(condition){ // can access obj[prop] and obj here
obj.children = example.getData(...); // getData returns a promise
return obj.children; // return the promise.
}
});
});
Promise.resolve(obj.children).then(function(children){
// here the async call to get `.children` is done.
// can wait for `p` too (the loop) if we care about it
if(obj.length === 10) // do stuff
});
这篇关于使得异步在一个循环中的JavaScript任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!