Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await equivalent of 'Promise.resolve().then()'?

Tags:

I'm familiar with Promises, but have inherited some rather unusual code that, rather than making a new Promise(), uses the following:

Promise.resolve().then(   function() {     // Do useful things   } ) 

From my research, this is a weird version of setImmediate - ie, run the following function on the next tick.

What would be the await version of this?

like image 842
mikemaccana Avatar asked Jul 13 '17 11:07

mikemaccana


People also ask

Is await the same as promise resolve?

Promise creation starts the execution of asynchronous functionality. await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves.

Is then equivalent to await?

Async/await and then() are very similar. The difference is that in an async function, JavaScript will pause the function execution until the promise settles. With then() , the rest of the function will continue to execute but JavaScript won't execute the .

What is promise resolve () then?

resolve() The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

Can you await a promise resolve?

await is a new operator used to wait for a promise to resolve or reject. It can only be used inside an async function. Promise. all returns an array with the resolved values once all the passed-in promises have resolved.


2 Answers

There may be two different reasons for the Promise.resolve(). You touched on one of them:

Defer until the end of the current run of the JS event loop

Here the obvious answer is await Promise.resolve();.

await undefined does the same thing implicitly, but why not be explicit?

Singular error handling

Promise.resolve() is also often seen at the head of a promise chain for singular error handling:

const doSomething = x => new Promise(r => setTimeout(() => r(x), 1000));  Promise.resolve() .then(() => doSomething(""())) // bug! .then(() => doSomething("else")) .catch(e => console.log("Got " + e)); // Got TypeError: "" is not a function

Without it, the first step may throw an exception instead, which may be unexpected!

const doSomething = x => new Promise(r => setTimeout(() => r(x), 1000));  doSomething(""()) // bug! .then(() => doSomething("else")) .catch(e => console.log("Got " + e)); // uncaught!

Here the answer is: you no longer need the Promise.resolve() prologue with async/await.

async functions implicitly catch synchronous exceptions and return a rejected promise instead, guaranteeing singular error handling and a promise return value:

const doSomething = x => new Promise(r => setTimeout(() => r(x), 1000));  (async () => {   await doSomething(""()); // bug!   await doSomething("else"); })().catch(e => console.log("Got " + e)); // Got TypeError: "" is not a function

Not only is this a nice invariant and less to type, unlike the Promise.resolve() kludge, it actually still calls doSomething synchronously:

function doSomething() {   console.log("doSomething() called");   ""() // bug!   return new Promise(r => setTimeout(() => r(x), 1000)); }  (async () => {   await doSomething();   await doSomething("else"); })().catch(e => console.log("Got " + e)); // Got TypeError: "" is not a function  console.log("here");

This would be pretty hard to pull off any other way. Another reason async/await is great!

like image 84
jib Avatar answered Oct 27 '22 01:10

jib


Just await something.

If you give await an expression which is not a promise, it will behave like

await Promise.resolve(<nonPromiseExpression>) 

So await undefined will cause the rest of the async function to be executed asynchronously. Take these two implementations of setImmediate as an example:

var setImmediate = function (fn) {    Promise.resolve().then(fn);  };    console.log('A');  setImmediate(function () {    console.log('E');  });  console.log('B');    setImmediate = async function (fn) {    await undefined;    fn();  };    console.log('C');  setImmediate(function () {    console.log('F');  });  console.log('D');
like image 31
PeterMader Avatar answered Oct 27 '22 01:10

PeterMader