Does awaiting a non-Promise have any detectable effect?

后端 未结 2 794
你的背包
你的背包 2020-12-09 08:20

One can await a non-Promise and that\'s good so.

All these expressions are valid and cause no error:

await 5
await \'A\'
await {}
await          


        
2条回答
  •  半阙折子戏
    2020-12-09 08:27

    await is not a no-op. If the awaited thing is not a promise, it is wrapped in a promise, that promise is awaited. Therefore await changes the execution order (but you should not rely on it nevertheless):

    console.log(1);
    (async function() {
      var x = await 5; // remove await to see 1,3,2
      console.log(3);
    })();
    console.log(2);
    

    Additionally await does not only work on instanceof Promises but on every object with a .then method:

    await { then(cb) { /* nowhere */ } };
    console.log("will never happen");
    

    Is there any detectable effect of awaiting a non-Promise?

    Sure, .then gets called if it exists on the awaited thing.

    Is there any difference in behavior one should be aware of to avoid a potential error?

    Don't name a method "then" if you don't want it to be a Promise.

    Any performance differences?

    Sure, if you await things you will always defer the continuation to a microtask. But as always: You won't probably notice it (as a human observing the outcome).

提交回复
热议问题