I have an object whose value comes from an AJAX request. I'm converting it to a promise and am encountering some behaviour with promises that I don't expect. I have an example here that exhibits the same behaviour, but I'm substituting Q.all() for my AJAX request.
(Thing = function(){
var promise;
var refresh = function() {
promise = Q.all(["a", "b"]);
};
var fetch = function(i) {
return promise.then(function(promiseVal){
return promiseVal[i];
});
};
refresh();
return {
"fetch": fetch,
"refresh": refresh,
"promise": promise
};
}());
Thing is executed on load and runs "refresh" to populate itself initially. The point of the "fetch" function is that my async request (Q.all in this case) returns a promise for an array, but what I really want is a promise for elements in the array (e.g. a promise for "a" or a promise for "b"). So I'm expecting Thing.fetch(1)
to return a promise for "b".
Thing.fetch(1)
does return a promise, but if I do Thing.fetch(1).valueOf()
it returns a promise, not "b" as I was expecting. If I do:
Thing.fetch(1).then(function(foo){
console.log(foo);
});
it will print "b" on the console.
If I do Thing.promise.valueOf()
it returns the array, so the promise is resolved when I call "fetch".
So my question is why doesn't valueOf() return a value when I call it on the promise returned by "fetch"?