JavaScript async/await

In JavaScript, asynchronous code can be done many different ways. The most recent, and most readable, is using the async/await syntax to deal with promises.

If you’ve seen promises, you’ll know the syntax is pretty awful. Very difficult to understand …


This content originally appeared on DEV Community and was authored by Joe Enos

In JavaScript, asynchronous code can be done many different ways. The most recent, and most readable, is using the async/await syntax to deal with promises.

If you've seen promises, you'll know the syntax is pretty awful. Very difficult to understand until you've actually done it several times, and even then it's easy to screw up.

The async/await syntax makes your code look synchronous, while still functioning the same way as it would with a promise.

To do it, you just mark a function as async, then await another promise. Your function automatically becomes a promise, and can be consumed with await or the old fashioned promise syntax:

async function go() {
    try {
        console.log(await callSomePromise(3));
    } catch (ex) {
        console.log(ex);
    }
    try {
        console.log(await callSomePromise(4));
    } catch (ex) {
        console.log(ex);
    }
}

// treat go() as a regular promise or you can use async/await again
go().then(() => {
    console.log("go is done");
});

See it in action here:


This content originally appeared on DEV Community and was authored by Joe Enos


Print Share Comment Cite Upload Translate Updates
APA

Joe Enos | Sciencx (2021-05-23T23:53:39+00:00) JavaScript async/await. Retrieved from https://www.scien.cx/2021/05/23/javascript-async-await/

MLA
" » JavaScript async/await." Joe Enos | Sciencx - Sunday May 23, 2021, https://www.scien.cx/2021/05/23/javascript-async-await/
HARVARD
Joe Enos | Sciencx Sunday May 23, 2021 » JavaScript async/await., viewed ,<https://www.scien.cx/2021/05/23/javascript-async-await/>
VANCOUVER
Joe Enos | Sciencx - » JavaScript async/await. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/23/javascript-async-await/
CHICAGO
" » JavaScript async/await." Joe Enos | Sciencx - Accessed . https://www.scien.cx/2021/05/23/javascript-async-await/
IEEE
" » JavaScript async/await." Joe Enos | Sciencx [Online]. Available: https://www.scien.cx/2021/05/23/javascript-async-await/. [Accessed: ]
rf:citation
» JavaScript async/await | Joe Enos | Sciencx | https://www.scien.cx/2021/05/23/javascript-async-await/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.