Reputation: 1146
How do I write this code using async, await only:
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(‘done’)
}, 1000)
}
Upvotes: 2
Views: 76
Reputation: 371138
You can't. What async
and await
do is they can replace .then
s, eg:
function foo(someProm) {
return someProm.then(() => {
console.log('someProm done');
});
}
can turn into
async function foo(someProm) {
await someProm;
console.log('someProm done');
}
They can also automatically wrap their return value in a Promise if the return value is synchronous - eg
async function foo() {
return '2';
}
will return a Promise which resolves to 2.
But async
and await
cannot replace the generic Promise constructor. If you have a callback-based API, and you want a Promise that resolves when the callback finishes, you can't use async
and await
for that task - you must use new Promise
as you're doing here.
There's one exception which is barely worth mentioning, and should not be used. In the particular case of setTimeout
, when nothing else needs to be done between the time the Promise is created and when it resolves, it's theoretically possible to create an async
function which blocks for however many seconds you need, and then resolves:
console.log('start');
// Putting this in a setTimeout so that "start" logs above
// before the below code starts blocking
setTimeout(() => {
const theProm = (async () => {
const t0 = performance.now();
while (performance.now() - t0 < 1000);
})();
theProm.then(() => {
console.log('done');
});
}, 100);
(For informational purposes only. Do not use that code)
Upvotes: 3