2017-02-23 42 views
0

我从具有以下响应格式的API提取信息:在Node.js的,异步递归函数解决空头支票

{ 
    items: [{}, {}, {}], 
    nextPage: { 
    startIndex: 11 
    } 
} 

,所以我写了这个程序来检查,如果有一个nextPage属性,并使用offset = startIndex向API发出后续请求。这里是我的代码:

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; 
}; 

代码的那部分工作得很好,问题就出现了,当我试图调用search功能我写的是这样的:

let promises = keywords.map((keyword) => { 
    return Serps.search(keyword, startIndex, serps); 
    }); 

    q.allSettled(promises) 
    .then((results) => { 
    console.log(results); // [ { state: 'fulfilled', value: undefined } ] 
    } 

我的问题是,承诺正在实现,但价值是不确定的。

那么我做错了什么,我该如何解决?

回答

0

我这里通过不返回一个空的承诺,解决了这个问题:

this.search(query, result.queries.nextPage[0].startIndex, serps) 
    .then(() => { 
     deferred.resolve(serps); 
    }); 

我仍然需要扁平化的结果,所以也许有一个聪明的解决方案,到目前为止完美的作品。