let user = { name: "dominic" };
let promise = new Promise(function (resolve, reject) {
setTimeout(() => resolve(user), 1000);
});
let readPromise = async () => {
let data = await promise;
return data;
};
console.log(readPromise()); // returns Promise { <pending> }
// how do I get it to return { name }
1 Like
like this:
readPromise().then(function(result){
console.log(result)
});
1 Like
i thought the point of async was so that i didnt have to use .then
you have to await
for a promise to resolve. If you go at it sync (like in your example), you will see a pending promise logged out.
Edit:
Oh, I see what is confusing. You await inside the wrapper and expect it to be resolved. Well, same thing happens what I explained above. Async functions always return a promise, so you get a pending promise (from that anonymous function) returned to you.
Try this:
await (async () => ... )
or this:
console.log(await readPromise())
Just remember, that top level await is only available since node v14.8 or Chrome v89.
If you need to support an older version you should use IIFE:
(async function () {
let user = { name: "dominic" };
let promise = new Promise(function (resolve, reject) {
setTimeout(() => resolve(user), 1000);
});
let readPromise = async () => {
let data = await promise;
return data;
};
console.log(await readPromise());
})();
1 Like
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.