You can use the async
and await
keywords to write asynchronous code that looks and behaves like synchronous code.
async function getData() {
try {
const result = await someAsyncOperation();
console.log(result);
} catch (error) {
console.error(error);
}
}
To use await
, the function that contains it must be marked with the async
keyword. The await
keyword can then be used to wait for a Promise to be resolved. In the example above, someAsyncOperation()
is an async function that returns a Promise. The await
keyword waits for the Promise to be resolved, and then assigns the resolved value to the result
variable.
If the Promise is rejected, the catch
block will be executed.
You can use async
/await
with any async function, whether it's a third-party library or something you wrote yourself. It can make your asynchronous code much easier to read and understand.