I am attempting a basic concept that is still eluding me… In the option (that is commented out) including the Start().then… I’m able to nest the functions so that they start and end in the desired order. In the await version, they start & end in the appropriate order but I’m not clear how I’m meant to put in log the resolve text after each one has completed. Sorry this is basic…
console.log("Synchronous result."); function Start() { return new Promise(function (resolve) { console.log(`Starting the Start`); setTimeout(() => resolve("Start has finished"), 5000); }); } function Middle() { return new Promise(function (resolve) { console.log(`Starting the Middle`); setTimeout(() => resolve("Middle has finished"), 2000); }); } function End() { return new Promise(function (resolve) { console.log(`Starting the End`); setTimeout(() => resolve("End has finished"), 1000); }); } // this works in the traditional promise method /* Start().then((result) => { console.log(result), Middle().then((result) => { console.log(result), End().then((result) => { console.log(result); }); }); }); */ // now trying async/await async function workflow() { let call1 = await Start(); let call2 = await Middle(); let call3 = await End(); } workflow();
Advertisement
Answer
Well, you almost have it. In an async function, the await will return the result of the promise. So all you have to do is do the console.log after.
console.log("Synchronous result."); function Start() { return new Promise(function (resolve) { console.log(`Starting the Start`); setTimeout(() => resolve("Start has finished"), 5000); }); } function Middle() { return new Promise(function (resolve) { console.log(`Starting the Middle`); setTimeout(() => resolve("Middle has finished"), 2000); }); } function End() { return new Promise(function (resolve) { console.log(`Starting the End`); setTimeout(() => resolve("End has finished"), 1000); }); } // this works in the traditional promise method /* Start().then((result) => { console.log(result), Middle().then((result) => { console.log(result), End().then((result) => { console.log(result); }); }); }); */ // now trying async/await async function workflow() { let call1 = await Start(); console.log(call1); let call2 = await Middle(); console.log(call2); let call3 = await End(); console.log(call3); } workflow();