2017-02-23 51 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); 
    }); 

我仍然需要扁平化的結果,所以也許有一個聰明的解決方案,到目前爲止完美的作品。