Async/Await by Examples

node v10.24.1
version: 1.0.0
endpointsharetweet
function slowFunction(message) { return new Promise((resolve, reject) => { setTimeout(() => { resolve("DONE: " + message); }, 3000) }); } // All Promise.all([slowFunction("Alice"), slowFunction("Bob"), slowFunction("Charlie")]) .then((res) => { console.log(res); }); // Sequential slowFunction("Alice") .then((res) => { console.log(res); return slowFunction("Bob"); }) .then((res) => { console.log(res); return slowFunction("Charlie"); }).then((res) => { console.log(res); });
now, using async await
async function slowFunction2(message) { let myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve("DONE: " + message); }, 3000) }); let result = await myPromise; return result; } // Sequential console.log(await slowFunction("W")); console.log(await slowFunction("X")); console.log(await slowFunction2("Y")); console.log(await slowFunction2("Z")); console.log("done sequence");
Loading…

no comments

    sign in to comment