让angular.forEach等待承诺将下一个对象后, [英] Make angular.forEach wait for promise after going to next object

查看:667
本文介绍了让angular.forEach等待承诺将下一个对象后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的列表。对象被传递到一个延迟函数。我想打电话给下一个对象的函数的previous呼叫解决之后。有没有什么办法可以做到这一点?

  angular.forEach(对象,函数(对象){
    //等待此解决,之后移动到下一个对象
    DoSomething的(对象);
});


解决方案

您不能使用 .forEach()如果你想等待一个承诺。 Javascript和承诺只是不这样的。


  1. 您可以链的多个承诺,使他们的承诺的基础设施序列。


  2. 您可以手动迭代,推进循环只有当previous承诺完成。


  3. 您可以像使用库异步将测序它们。


有许多不同的选择,但 .forEach()你也不会做。


以下是使用角度的承诺的承诺链接序列的一个例子(假设对象是一个数组):

  objects.reduce(功能(P,VAL){
    返回p.then(函数(){
        返回DoSomething的(VAL);
    });
} $ q.when(真))。然后(功能(finalResult){
    //这里完成
},功能(错误){
    //此处错误
});

和使用标准ES6的承诺,这将是:

  objects.reduce(功能(P,VAL){
    返回p.then(函数(){
        返回DoSomething的(VAL);
    });
},Promise.resolve())。然后(功能(finalResult){
    //这里完成
},功能(错误){
    //此处错误
});


下面是手动排序(假设对象是一个数组)为例,虽然这不报到完毕或错误,就像上面的选项所做的:

 函数运行(对象){
    变种CNTR = 0;    接下来的功能(){
        如果(CNTR< objects.length){
            DoSomething的(对象[C​​NTR ++]),然后(下)。
        }
    }
    下一个();
}

I have a list of objects. The objects are passed to a deferred function. I want to call the function with the next object only after the previous call is resolved. Is there any way I can do this?

angular.forEach(objects, function (object) {
    // wait for this to resolve and after that move to next object
    doSomething(object);
});

解决方案

You can't use .forEach() if you want to wait for a promise. Javascript and promises just don't work that way.

  1. You can chain multiple promises and make the promise infrastructure sequence them.

  2. You can iterate manually and advance the iteration only when the previous promise finishes.

  3. You can use a library like async that will sequence them for you.

There are lots of different alternatives, but .forEach() will not do it for you.


Here's an example of sequencing using chaining of promises with angular promises (assuming objects is an array):

objects.reduce(function(p, val) {
    return p.then(function() {
        return doSomething(val);
    });
}, $q.when(true)).then(function(finalResult) {
    // done here
}, function(err) {
    // error here
});

And, using standard ES6 promises, this would be:

objects.reduce(function(p, val) {
    return p.then(function() {
        return doSomething(val);
    });
}, Promise.resolve()).then(function(finalResult) {
    // done here
}, function(err) {
    // error here
});


Here's an example of manually sequencing (assuming objects is an array), though this does not report back completion or errors like the above option does:

function run(objects) {
    var cntr = 0;

    function next() {
        if (cntr < objects.length) {
            doSomething(objects[cntr++]).then(next);
        }
    }
    next();
}

这篇关于让angular.forEach等待承诺将下一个对象后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆