Async / Await only works with functions that return (and resolve) a promise.
The following example will be written to the console after 3 seconds, and then continue.
// Tell the browser that this function is asynchronous async function myFunc() { // Await for the promise to resolve await new Promise((resolve) => { setTimeout(() => { // Resolve the promise resolve(console.log('hello')); }, 3000); }); // Once the promise gets resolved continue on console.log('hi'); } // Call the function myFunc();
Without async / await, the output would look like this:
hi hello
This will be due to the fact that hi output will be started, and then after 3 seconds a timeout will be executed.
But with async / await, the output is as follows:
hello hi
This is because we are waiting for a timeout, then we run the output of hi .
source share