What is the difference between:
await new Promise(resolve => setTimeout(resolve, 5000));
await setTimeout(resolve, 5000);
What is the difference between:
await new Promise(resolve => setTimeout(resolve, 5000));
await setTimeout(resolve, 5000);
await setTimeout(resolve, 5000);
does nothing extra, it's the same as setTimeout(resolve, 5000);
await
will pause code execution of the containing function until a promise is resolved. The setTimeout
function does not return a promise, it is not an async
function. Hence, await
is redundant, it doesn't do anything special in this case.
Your first bit of code does return a promise. It takes the legacy non-promise-based setTimeout
function and turns it into a promise form. It then awaits this promise form.
You should learn about promises to gain a better understanding of what's going on. The key thing to note here is the difference between callback-based functions (like setTimeout) and modern promise-based functions.