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

2019-03-24 12:32发布

I'm still unclear on the difference between calling a resolver's resolve() vs fulfill()? I see both the functions and the terms "resolve a promise" and "fulfill a promise" batted around a lot.

When should I be using each?

2条回答
Emotional °昔
2楼-- · 2019-03-24 12:54

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.

查看更多
闹够了就滚
3楼-- · 2019-03-24 13:15

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.

查看更多
登录 后发表回答