1

I am using the Q library of node.js . I am trying to print a report which would print the query name and the result . This is what I have . The code prints "In function undefined . How do I access the value of the promise object from within the "then" function ?

var queries = ["2091 OR 2092 OR 2093", 
            "2061 OR 2062",
            "2139 OR 2140 OR 2141"
            ];

var promises = new Array();
for (var i=0; i<queries.length; i++) {
    promises[i]=performSearch(queries[i]);
    promises[i].query = queries[i];
    console.log("Outside function ", promises[i].query);

    promises[i].then(function(data) {
            console.log("In function ", this.query);
            processSearchResults(data,this.query);
    });
}
Q.allSettled(promises).then(function(results) {
    endFunction();
});

1 Answers1

1

This is what I have:

promises[i].then(function(data) {
        console.log("In function ", this.query);
        processSearchResults(data,this.query);
});

The code prints "In function undefined".

The spec mandates that the callback is called with nothing for the this value, so this will refer to the global (window) object in sloppy mode, which does not have a .query property. In strict mode you'd have gotten an exception when this was undefined.

How do I access the value of the promise object from within the "then" function ?

There is no special method. You usually will not need to access a promise as an object, it's only a transparent value representing the single result of an asynchronous computation. All you need to do with it is to call its .then() method - and inside the callback, there's no reason to access the promise object, because the information it holds is already accessible to you (data, and the fact that the fulfillment callback was invoked).

So if you want to access your .query property, you'd have to use promises[i] as usual. However, you will need a closure for i so you'd better use map anyway and hold the query string in the closure directly instead of making it a property on a promise object:

var queries = ["2091 OR 2092 OR 2093", 
            "2061 OR 2062",
            "2139 OR 2140 OR 2141"
            ];

var promises = queries.map(function(query) {
    var promise = performSearch(query);
    console.log("Outside function ", query);
    var processedPromise = promise.then(function(data) {
        console.log("In function ", query);
        return processSearchResults(data, query);
    });
    return processedPromise; // I assume you don't want the unprocessed results
});
Q.allSettled(promises).then(function(processedResults) {
    endFunction(processedResults);
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375