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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.