To wait for a promise to resolve in JavaScript, you can use the await
keyword inside an async
function. For example:
async function example() {
// Wait for the promise to resolve
const result = await somePromise();
// Use the result of the promise
console.log(result);
}
Code language: JavaScript (javascript)
Alternatively, you can use the .then()
method to handle the resolved value of the promise. For example:
somePromise()
.then(result => {
// Use the result of the promise
console.log(result);
});
Code language: JavaScript (javascript)
It’s important to note that await
can only be used inside an async
function, and the async
function will pause at the await
keyword until the promise is resolved. This allows you to write asynchronous code that looks and behaves like synchronous code.
Real-World Example
Here is an example of using await
to wait for a promise to resolve in a real-world scenario:
async function getUserData(userId) {
// Wait for the API request to complete
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
// Wait for the response to be converted to JSON
const user = await response.json();
// Return the user data
return user;
}
// Use the getUserData function
getUserData(1).then(user => {
console.log(user);
// Output: { id: 1, name: 'Leanne Graham', ... }
});
Code language: JavaScript (javascript)
In this example, the getUserData
function makes an API request using fetch
and waits for the response using await
. It then waits for the response to be converted to JSON and returns the resulting user object.
This allows the code to be written in a synchronous-looking style, even though it is making asynchronous API requests.
Leave a Reply