How to do it...

  1. Open your command-line application and navigate to your workspace.
  2. Create a new folder named 3-06-using-promise-all.
  3. Copy or create an index.html that loads and runs a main function from main.js.
  1. 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'); 
}  
  1. 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;  
}   
  1. 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); 
  }); 
}    
  1. 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; 
}  
  1. 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'); }
  1. 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);
});
  1. Start your Python web server and open the following link in your browser: 
    http://localhost:8000/.

  1. You should see the following output:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.108.196