如何确保Dojo 1.10中两个Deferred的then回调均执行完成?
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/alltakes 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 frompromise1, the second frompromise2.
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

