Я не могу получить 100 результатов в API пользовательского поиска Google в цикле - PullRequest
0 голосов
/ 04 октября 2019

Я не могу получить первые 100 результатов для запроса в цикле. Я пытался получить следующие 10 результатов, изменив значение начального параметра. Но я хочу, чтобы он был в цикле.

 getResponse() {
    superagent.get('https://www.googleapis.com/customsearch/v1')
      .query({'q': this.search.current.value, 'cx': this.cx, 'gl': 'all', 'start': 1, 'num': 10, 'key': this.apiKey})

      .then((res) => {

        console.log('value of show', this.show)
        console.log('response', res)
        // let arr = res.body.items
        //   arr.map((value)=>{
        //      console.log('value', value)
        //      this.field =value
        //  })
        // this.field = arr
        this.setState({
          show: true,
          data: res.body.items || []
        })

      })
      .catch(err => {
        this.setState({
          show: false,
          data: []
        })
      })
  }

1 Ответ

0 голосов
/ 04 октября 2019

Примерно так может быть хорошей отправной точкой для вашего случая:

  getResponse() {
    const queries = [];
    let start = 1;

    while (start <= 100) {
      const query = superagent.get('https://www.googleapis.com/customsearch/v1')
      .query({'q': this.search.current.value, 'cx': this.cx, 'gl': 'all', 'start': start, 'num': 10, 'key': this.apiKey});
      queries.push(query);
      start += 10;
    }  
    Promise.all(queries)
      .then((responses) => {
        // responses will be an array of responses
        responses.forEach(function(res) {
          console.log('value of show', this.show)
          console.log('response', res)
          // let arr = res.body.items
          //   arr.map((value)=>{
          //      console.log('value', value)
          //      this.field =value
          //  })
          // this.field = arr
          this.setState({
            show: true,
            data: res.body.items || []
          })
        })
      })
      .catch(err => {
        this.setState({
          show: false,
          data: []
        })
      })
  }
...