3 ms·
Promises also solve this problem. If you immediately resolve a promise it isn't actually resolved until the next event loop "tick": new Promise(resolve =>
by tlrobinson 11y ago
Promises also solve this problem. If you immediately resolve a promise it isn't actually resolved until the next event loop "tick":
new Promise(resolve => resolve("resolved!")).then(result => console.log(result));
console.log("next statement");
Prints "next statement" then "resolved!".
- jallardice 11y agoYou don't even have to resolve the promise via a callback for that to be the case - you can use the static resolve method. This is really useful if you have a function that can sometimes return a promise and sometimes a "normal" value. Promise.resolve("resolved!").then(result => console.log(result)); console.log("next statement");
- mistercow 11y agoIt's actually not the next event loop tick (or it's not supposed to be; some implementations get this wrong). Promises use microtasks, so an already-resolved promise dispatches at the end of the current tick.