Asynchronous JavaScript


Once you get the hang of javascript promises, you might like async await, which is just "syntactic sugar" on topof promises. In the following example we create an async function and within that we await the greeter promise.

const greeter = new Promise((res, rej) => { setTimeout(() => res('Hello world!'), 2000); }); async function myFunc() { const greeting = await greeter; console.log(greeting); } myFunc(); // 'Hello world!'
                

Async functions return a promiseOne important thing to note here is that the result of an async function is a promise.

const greeter = new Promise((res, rej) => { setTimeout(() => res('Hello world!'), 2000); }); async function myFunc() { return await greeter; } console.log(myFunc()); // => Promise {} myFunc().then(console.log); // => Hello world!
              

Console.

const second = () => { setTimeout(() => { console.log('Second') }, 2000) } const first = () => { console.log('Hey There') second() console.log('The End') } first() const getIDs = new Promise((resolve, reject) => { setTimeout(() => { resolve([1, 2, 3, 4, 5]) }, 1500) }) getRecipeAW = async () => { const IDs = await getIDs console.log(IDs) const ids = await getIDs console.log(ids) } getRecipeAW()