You can call an async function within a Promise
.then()
method in JavaScript using the await
keyword. The await
keyword can be used to wait for a Promise
to resolve before moving on to the next line of code. Here’s an example:
function myAsyncFunction() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Async function resolved");
}, 2000);
});
}
function myPromiseFunction() {
return new Promise((resolve, reject) => {
myAsyncFunction().then(asyncResult => {
// Log the result of the async function
console.log(asyncResult);
// Call another async function using the await keyword
const result = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const json = await result.json();
// Log the result of the second async function
console.log(json);
// Resolve the main promise
resolve("Promise function resolved");
});
});
}
myPromiseFunction().then(result => {
console.log(result);
});
In this example, we define an async function myAsyncFunction()
that returns a Promise
that resolves after a 2-second delay. We then define a Promise
function myPromiseFunction()
that calls myAsyncFunction()
using the .then()
method. Within the .then()
method, we use the await
keyword to call another async function, fetch()
, which retrieves some JSON data from a web API.
After the fetch()
call, we log the result of both the myAsyncFunction()
and fetch()
calls, and then resolve the main promise using the resolve()
method. Finally, we call myPromiseFunction()
and attach a .then()
method to log the result of the main promise.
Note that if you want to catch any errors that occur in the async function or the Promise function, you can use the catch()
method to handle them. For example, you could add the following code to catch errors:
myPromiseFunction()
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
This code logs any errors that occur to the console using the console.error()
method.
+ There are no comments
Add yours