确保一组 deferred.then 回调完成

Ensure a set of deferred.then callbacks completes

顺便说一句,我正在使用 Dojo 1.10DeferredPromise API。所以场景如下:

 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 中的延迟对象回调函数在 运行 另一个函数之前完成。

使用 Promise.all 创建一个仅在您传递给它的所有承诺都已解决后才解决的承诺。请注意,您必须保存对新承诺的引用:

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);

您可以使用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"
  });

});