最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Wait execution of a new inner promise - Stack Overflow

programmeradmin2浏览0评论

I'm new to this promises world and I got quite a situation I don't know what to do.

I have a new promise been called by the result of the first promise.

Here is the situation:

    function asyncCall(object){
           return firstObject.loadSomething(object).then(function(result) {
               result.innerAsyncCall().then(function() {
                    finalCode();
               });
           });
    }

I loop over asyncCall and build a $q.all().then() to wait for the promises to resolve.
However, since the inner promise is not chained it runs independently.
Sample Code:

var promises = [];
array.forEach(function(object){
     promises.push(asyncCall(object));
});

$q.all(promises).then(function(){
     console.log('Done!!');
});

The question is. What can I do to wait the full execution of the inner promise?

I'm new to this promises world and I got quite a situation I don't know what to do.

I have a new promise been called by the result of the first promise.

Here is the situation:

    function asyncCall(object){
           return firstObject.loadSomething(object).then(function(result) {
               result.innerAsyncCall().then(function() {
                    finalCode();
               });
           });
    }

I loop over asyncCall and build a $q.all().then() to wait for the promises to resolve.
However, since the inner promise is not chained it runs independently.
Sample Code:

var promises = [];
array.forEach(function(object){
     promises.push(asyncCall(object));
});

$q.all(promises).then(function(){
     console.log('Done!!');
});

The question is. What can I do to wait the full execution of the inner promise?

Share Improve this question edited Feb 17, 2016 at 18:10 Bergi 666k161 gold badges1k silver badges1.5k bronze badges asked Feb 17, 2016 at 17:57 ShoyoShoyo 3472 silver badges9 bronze badges 1
  • 1 You must only resolve the outer promise within the inner.. – enapupe Commented Feb 17, 2016 at 17:59
Add a ment  | 

1 Answer 1

Reset to default 10

If you resolve a promise with a promise, it will "recursively" adopt its state and wait for the innermost one. In the case of a .then() call, the new promise is resolved with the return value of the callback - so you just have to add a return to your code and it'll work:

function asyncCall(object) {
    return firstObject.loadSomething(object).then(function(result) {
        return result.innerAsyncCall().then(function() {
//      ^^^^^^
            finalCode();
        });
    });
}

Notice that you can also flatten this into a chain:

function asyncCall(object) {
    return firstObject.loadSomething(object).then(function(result) {
        return result.innerAsyncCall();
    }).then(finalCode);
}
发布评论

评论列表(0)

  1. 暂无评论