In jQuery, how does .state() determine whether a promise is pending, resolved or rejected

StackOverflow https://stackoverflow.com/questions/20559992

Вопрос

I don't understand what determines state of a promise object. What causes an object or function to have a state of "pending", while the $(".selector") to have state of "resolved".

Code as follows:

var obj = { prop: "value" };

var deferred = new $.Deferred();
var promiseObj1 = deferred.promise(obj);
var promiseObj2 = $(".selector").promise();

console.log(promiseObj1.state());    // "pending"
console.log(promiseObj2.state());    // "resolved"
Это было полезно?

Решение

By default the state of a promise is pending when it is created. The state of a promise is changed when the deferred object which created the promise either resolves/rejects it.

var obj = { prop: "value" };

var deferred = new $.Deferred();
var promiseObj1 = deferred.promise(obj);
var promiseObj2 = $(".selector").promise();

console.log(promiseObj1.state());    // "pending"
console.log(promiseObj2.state());    // "resolved"

In the case of promiseObj1 you are creating a promise but the deferred object which created it is neither rejected/resolved that is the reason for the pending state

In the case of promiseObj2(it is a promise which will be resolved when all the actions queued in the fx queue of the matched elements are completed) since there are no animations in progress by default it is considered as resolved.

Demo: Fiddle

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top