I'm pulling information from an API that has the following response format:
{
items: [{}, {}, {}],
nextPage: {
startIndex: 11
}
}
so I wrote this program that checks if there's a nextPage
property, and I make a subsequent request to the API with an offset = startIndex. Here's my code:
Serp.prototype.search = function(query, start, serps) {
let deferred = this.q.defer();
let url = '';
if (start === 0) {
url = `${GCS_BASE}/?key=${this.key}&cx=${this.cx}&q=${query}`;
} else {
url = `${GCS_BASE}/?key=${this.key}&cx=${this.cx}&q=${query}&start=${start}`;
}
this.https.get(url, (res) => {
let rawData = '';
res.on('data', (chunk) => {
rawData += chunk;
});
res.on('end', () => {
let contactInfo = [];
let result = JSON.parse(rawData);
let totalResults = result.searchInformation.totalResults;
// if total results are zero, return nothing.
if (totalResults === 0) {
serps.push(contactInfo);
deferred.resolve(serps);
// there's just one page of results.
} else if (totalResults <= 10) {
contactInfo = this._extractContactInfo(result.items, query.toLowerCase());
serps.push(contactInfo);
deferred.resolve(serps);
// if there are more than 10, then page through the response.
} else if ((totalResults > 10) && (result.queries.hasOwnProperty('nextPage'))) {
// recursively and asynchronously pull 100 results.
if (result.queries.nextPage[0].startIndex < 91) {
contactInfo = this._extractContactInfo(result.items, query.toLowerCase());
serps.push(contactInfo);
this.search(query, result.queries.nextPage[0].startIndex, serps)
.then(() => {
deferred.resolve();
});
} else {
contactInfo = this._extractContactInfo(result.items, query.toLowerCase());
serps.push(contactInfo);
let res = this.flatten(serps);
deferred.resolve(res);
}
}
});
});
return deferred.promise;
};
That part of the code works just fine, the problem arises when I'm trying to call that search
function I wrote this way:
let promises = keywords.map((keyword) => {
return Serps.search(keyword, startIndex, serps);
});
q.allSettled(promises)
.then((results) => {
console.log(results); // [ { state: 'fulfilled', value: undefined } ]
}
My problem is that the promises are being fulfilled, but the value is undefined.
So what am I doing wrong, and how can I fix it?