You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确保Dojo 1.10中两个Deferred的then回调均执行完成?

Wait for Multiple Dojo Deferred then Callbacks to Complete

Hey there! Since you're using Dojo 1.10 with its built-in Deferred/Promise API, the perfect tool for this job is dojo/promise/all—it’s designed specifically to wait for multiple promises to finish before running a callback. Here's how to make it work for your scenario:

Key Background

Every then() call on a Deferred returns a new Promise that resolves only when the then callback finishes executing (whether it returns a direct value or another promise). We need to wait for both of these derived promises to resolve before triggering completeFunc.

Step-by-Step Implementation

First, import the dojo/promise/all module (it’s part of Dojo’s core promise utilities). Then wrap your two derived promises with all(), which creates a new promise that resolves only after both input promises are done.

Here’s your updated code:

// Import required Dojo modules
require(["dojo/promise/all", "dojo/Deferred"], function(all, Deferred) {
    var deferred_1 = new Deferred();
    // Capture the promise returned by deferred_1.then()
    var promise1 = deferred_1.then(function(value){
        // Your existing logic here
        return something;
    });

    var deferred_2 = new Deferred();
    // Capture the promise returned by deferred_2.then()
    var promise2 = deferred_2.then(function(value){
        // Your existing logic here
        return something;
    });

    var completeFunc = function(values){
        console.log("done");
        // Optional: Access results from each then callback
        // values[0] = return value from promise1, values[1] = return value from promise2
    };

    // Wait for both promises to resolve, then run completeFunc
    all([promise1, promise2]).then(completeFunc);

    // Don't forget to resolve your Deferreds somewhere in your code!
    // deferred_1.resolve(someTriggerValue);
    // deferred_2.resolve(anotherTriggerValue);
});

How It Works

  • dojo/promise/all takes an array of promises and returns a new aggregated promise.
  • This aggregated promise only resolves after every promise in the input array has successfully resolved.
  • When it resolves, it passes an array of results to completeFunc—the first element is the return value from promise1, the second from promise2.

Optional: Error Handling

If either then callback or original Deferred might reject, add an error handler to catch failures:

all([promise1, promise2])
    .then(completeFunc)
    .catch(function(error) {
        console.error("One of the promises failed:", error);
    });

内容的提问来源于stack exchange,提问作者Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:53:13