Are promises lazily evaluated?

吃可爱长大的小学妹 提交于 2021-01-27 12:19:43

问题


Is the code below guaranteed to output HERE?

var p = new Promise(() => console.log("HERE"))

(That is, does var p = new Promise(fn) always execute fn if p.then(…) is never called to do something with the result?)

More specifically, in the context of service workers, if I call Cache.delete() but never call .then() on the return value (or I throw away the return value), is the cache entry guaranteed to be deleted?


回答1:


Yes, it is guaranteed. The specification of Promise has this step which will always be evaluated:

  1. Let completion be Call(executor, undefined, «resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]]»).

where executor is what you passed to the Promise constructor, and Call results in that code being run. This all happens before the Promise is even returned to your p variable.




回答2:


As James said, it is guaranteed that the function will be called. Though this doesn't guarantee that the cache entry gets deleted!

You have to check the value of the promise resolution (true if the cache entry is deleted, false otherwise).



来源:https://stackoverflow.com/questions/35177230/are-promises-lazily-evaluated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!