onyeePeace

onyeePeace

Async/Await

Description

JavaScript is a synchronous programming language. This means that when code is executed, JavaScript starts at the top of the file and runs through the code line by line, until it is done. This means that only one thing can happen at one time.

Resource list

I have gotten some knowledge from this article: More on Async/Await

Async/Await in JavaScript allows for asynchronous performance to happen behind the scene without stopping other activities from going on. Once it is finished processing behind the scene, then the value is returned.

Async functions is used to write promise based code like it is synchronous without blocking the execution thread.

async function first() {
    return me;
}
first().then(alert); //result will be; me

The await operator is used to wait for a Promise till it returns a result. It can only be used inside an Async block and makes only the async function wait.

async function first() {
    let answer = new Promise((resolve, reject) => {
        setTimeout(() => {
            return resolve("Finished");
        }, 1000)
    });
    //await result from the promise
    let result = await answer;
    console.log(result);
}
first();

Using Async/Await with multiple promises takes some time. Until the first promise is resolved, the next promise will not execute. To combat this, the Promise.all( ) method is used. It returns a single promise that resolves after all of the promises passed into it has been resolved.

async function morePromise() {
    await Promise.all([promise1(), promise2()]);
    return "complete";
}
 
Share this