q.js: difference between resolve() and fulfill()

早过忘川 提交于 2019-12-03 10:29:32

You should use resolve. deferredPromise.resolve(nextPromise) means that anything waiting for deferredPromise will now wait for nextPromise. If nextPromise is not a promise at all, it gets turned into a fulfilled promise which goes on to inform anything waiting for it that the value has become available.

The fulfill method is a bad idea that will be deprecated and eventually go away entirely. fulfill is semantically equivalent to resolve in all useful cases. It’s only reason to exist is that deferredPromise.fulfill(value) is easier for humans to interpret than deferredPromise.resolve(value), since resolve is overloaded to handle both nextPromise and finalValue.

The problem with fulfill existing at all is that deferredPromise.fulfill(rejectedPromise) is semantically paradoxical.

In general, resolve means to EITHER succeed or fail. That is what triggers the invocation of the then actions. It can happen exactly once for any given promise.

fulfill means to "resolve" successfully. That will trigger the success callbacks in the then actions. The counterpart of "fulfill" for failure is reject.

From a different perspective, you can categorize the status of any promise at a particular point in time as "unresolved" (sometimes also called pending) or "resolved", and "resolved" has the sub-statuses of "fulfilled" and "rejected". A promise in "fulfilled" status has a value, and a promise in "rejected" status has a reason.

The particular methods in each API used to represent these notions differ. And unfortunately, there are many blog posts and documents out there which confuse these terms, in particular using "fullfill" when they mean "resolve" or vice versa.

Q

I do not know Q very well, but it appears that its resolve method actually fulfills the promise (emphasis added):

Calling resolve with a non-promise value causes promise to be fulfilled with that value.

The twist, however, is that you can also call deferred.resolve with a promise, in which case the first promise more or less assumes the state of the passed-in promise. For instance, if the passed-in promise is in "pending" state, the promise adopts the pending state of the passed promise. That implies the slightly odd semantics that a method named resolve actually does not resolve the promise.

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