When you mark a function as async
, you're essentially making it return a new Promise
object that resolves to whatever the function returns, and rejects if the function throws an error.
That means there are two ways to write simple async functions. These are both equivalent:
async function foo(data) {
return JSON.parse(data);
}
function foo(data) {
return new Promise((resolve, reject) => {
try {
resolve(JSON.parse(data));
} catch (e) {
reject(e);
}
});
}
Of course, the async
keyword lets you write simple asynchronous functions much more concisely and use more familiar syntax. But there are times where this isn't enough, because you can't actually return the value you want your Promise
to resolve to.
Usually you can retrieve a value asynchronously within an async
function using the await
keyword, but there are exceptions. Your example here is one of these exceptions.
Because your asynchronous function1
is not returning anything, so the Promise
resolves to undefined
. You should write your function to return a Promise
explicitly instead, so you can make sure it resolves with the value you want once that value is ready. Like this:
const function1 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('function 1 finished');
resolve('message');
}, 500);
});
};