Let's say I have the following async function. The console.log
will only fire after it has been resolved.
(async () => {
await new Promise(resolve => {
setTimeout(() => {
resolve();
}, 1000);
});
console.log('resolved');
})();
Is this valid JavaScript? Or should I always use .then()
? What are the drawbacks or behavioral differences from using .then()
here?
(async () => {
return await new Promise(resolve => {
setTimeout(() => {
resolve();
}, 1000);
});
})().then(() => {
console.log('resolved');
});
Off-topic: I also noticed the latest method return await
can be changed to just return
without the results changing, but this thread answered that question.