2017-02-23 10 views
0

を解決している私は、次の応答の形式を持っているAPIから情報を引っ張っています:は空約束に

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

私はまだ結果をフラット化する必要がある、ので、多分完璧に動作し、これまで賢くソリューションは、あります。