确保完成一组deferred.then回调

时间:2018-04-19 01:33:32

标签: javascript promise dojo deferred

我按照Dojo 1.10Deferred API附带的方式使用Promise。所以场景如下:

 var deferred_1 = new Deferred();
 deferred_1 .then(function(value){
  // do something
  return something;
 })

 var deferred_2 = new Deferred();
 deferred_2.then(function(value){
  // do something
  return something;
 })

var completeFunc = function(value){
    console.log("done");
}

//run completeFunc after completion of both deferred_1.then and 
deferred_2.then

如何确保在运行其他函数之前完成deferred_1.thendeferred_2.then中的延迟对象回调函数的完成。

2 个答案:

答案 0 :(得分:4)

使用Promise.all创建一个Promise,只有在您传入的所有承诺都解析后才能解析。请注意,您必须保存对新承诺的引用:

const deferred_1 = new Deferred();
const d1 = deferred_1.then(function(value) {
  // do something
  return something;
});
const deferred_2 = new Deferred();
const d2 = deferred_2.then(function(value) {
  // do something
  return something;
})
const completeFunc = function(value) {
  console.log("done");
}
Promise.all([d1, d2]).then(completeFunc);

答案 1 :(得分:0)

您可以使用dojo / promise / all功能。 documentation的示例:

require(["dojo/promise/all"], function(all){

  all([promise1, promise2]).then(function(results){
    // results will be an Array
  });

  // -- or --

  all({
    promise1: promise1,
    promise2: promise2
  }).then(function(results){
    // results will be an Object using the keys "promise1" and "promise2"
  });

});