How are the 'async' and 'await' keywords used in JavaScript?
Answer
The async
and await
keywords were introduced in ES2017 and provide a way to write asynchronous code that looks and behaves like synchronous code. The async
keyword is used to define an asynchronous function, which will always return a promise. The await
keyword can be used inside an async
function to pause the execution of the function until a promise is resolved. Here's an example of how async
and await
can be used to fetch data from a remote server:
async function fetchData() { try { const response = await fetch('https://example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error(error); } }
In this example, the fetchData
function is declared as an async
function, which means that it will always return a promise. Inside the function, the await
keyword is used twice: first to wait for the response from the server, and then to wait for the data to be parsed as JSON. The try...catch
block is used to handle any errors that may occur during the asynchronous operation.
Related JavaScript job interview questions
What are the ES6+ features you use?
JavaScript JuniorWhat is an event loop in JavaScript?
JavaScript JuniorWhat is 'this' keyword in JavaScript?
JavaScript JuniorCan you tell me what a promise is?
JavaScript JuniorCan you name two programming paradigms important for JavaScript app developers?
JavaScript Junior