2016-06-28 39 views
-1

标题很混乱,对不起。如何解决对另一个承诺的承诺?

我需要看看后续承诺的承诺内容。

见我以前的线程上下文:How to sequentially handle asynchronous results from API?

我在下面工作的代码,我注解我的问题:

var promises = []; 

    while (count) { 
     var promise = rp(options); 
     promises.push(promise); 
     // BEFORE NEXT PROMISE, I NEED TO GET ID OF AN ELEMENT IN THIS PROMISE'S DATA 
     // AND THEN CHANGE 'OPTIONS' 
    } 

    Promise.all(promises).then(values => { 
     for (var i = 0; i < values; i++) { 
      for (var j = 0; j < values[i].length; j++) { 
       results.push(values[i][j].text); 
      } 
     } 
     return res.json(results); 
    }, function(reason) { 
     trace(reason); 
     return res.send('Error'); 
    }); 
+0

'接受的答案是重要的,因为它既奖励海报解决您的问题,并通知其他人,你的问题是resolved.'我检查你的上下文线程,你有没有做过与它 – Oxi

+0

什么,我仍然在解决问题的过程中,只是有一个快速跟进问题。感谢提醒我接受答案。 @Oxi –

回答

0

这是一个承诺,怎么可以链接一个很好的例子,因为结果then是一个新的承诺。

while (count) { 
    var promise = rp(options); 
    promises.push(promise.then(function(result) { 
     result.options = modify(result.options); // as needed 
     return result.options; 
    }); 
} 

通过这种方式,可以对Promise.all的每个承诺进行预处理。

0

如果一个承诺依赖于另一个承诺(例如,直到前一个承诺完成并提供一些数据才能执行),那么您需要链接承诺。没有“达成承诺获得一些数据”。如果你想要它的结果,你可以用.then()等待它。

rp(options).then(function(data) { 
    // only here is the data from the first promise available 
    // that you can then launch the next promise operation using it 
}); 

如果你想做到这一点序列count倍(这是你的代码意味着什么),那么你可以创建一个包装功能,直到到达数从每个承诺完成调用本身。

function run(iterations) { 
    var count = 0; 
    var options = {...}; // set up first options 
    var results = [];  // accumulate results here 

    function next() { 
      return rp(options).then(function(data) { 
       ++count; 
       if (count < iterations) { 
        // add anything to the results array here 
        // modify options here for the next run 
        // do next iteration 
        return next(); 
       } else { 
        // done with iterations 
        // return any accumulated results here to become 
        // the final resolved value of the original promise 
       } 
      }); 
    } 
    return next(); 
} 

// sample usage 
run(10).then(function(results) { 
     // process results here 
}, function(err) { 
     // process error here 
}); 
+0

@MelvinLu - 这是否解决了您的问题或回答了您的问题? – jfriend00