- ECMAScript Cookbook
- Ross Harrison
- 265字
- 2021-08-27 19:27:42
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named 3-06-using-promise-all.
- Copy or create an index.html that loads and runs a main function from main.js.
- Create a main.js file that creates an object named rocket, and calls Promise.all with an empty array as the first argument:
export function main() { console.log('Before promise created'); const rocket = {}; Promise.all([]) console.log('After promise created'); }
- Create a function named addBoosters that creates an object with boosters to an object:
function addBoosters (rocket) { console.log('attaching boosters'); rocket.boosters = [{ count: 2, fuelType: 'solid' }, { count: 1, fuelType: 'liquid' }]; return rocket; }
- Create a function named performGuidanceDiagnostic that returns a promise of a successfully completed task:
function performGuidanceDiagnostic (rocket) { console.log('performing guidance diagnostic'); return new Promise(function (resolve) { setTimeout(function () { console.log('guidance diagnostic complete'); rocket.guidanceDiagnostic = 'Completed'; resolve(rocket); }, 2000); }); }
- Create a function named loadCargo that adds a payload to the cargoBay:
function loadCargo (rocket) { console.log('loading satellite'); rocket.cargoBay = [{ name: 'Communication Satellite' }] return rocket; }
- Use Promise.resolve to pass the rocket object to these functions within Promise.all:
export function main() { console.log('Before promise created'); const rocket = {}; Promise.all([
Promise.resolve(rocket).then(addBoosters),
Promise.resolve(rocket).then(performGuidanceDiagnostic),
Promise.resolve(rocket).then(loadCargo)
]); console.log('After promise created'); }
- Attach a then call to the chain and log that the rocket is ready for launch:
const rocket = {}; Promise.all([ Promise.resolve(rocket).then(addBoosters), Promise.resolve(rocket).then(performGuidanceDiagnostic), Promise.resolve(rocket).then(loadCargo) ]).then(function (results) {
console.log('Rocket ready for launch');
console.log(results);
});
Start your Python web server and open the following link in your browser:
http://localhost:8000/.
- You should see the following output:
![](https://epubservercos.yuewen.com/C944E7/19470395501577006/epubprivate/OEBPS/Images/b12bfb42-682b-46de-8112-3776f098ffc0.png?sign=1739569445-EBMC4vYm2X7Drr7dHRsPd8CqvQQPCR89-0-66310583871e47081cd1ce58986d01de)