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:
Top comments (0)