【问题标题】:making multiple api calls based on the size of the array根据数组的大小进行多次 api 调用
【发布时间】:2018-12-17 18:16:45
【问题描述】:

我正在尝试根据数组中的信息进行多个 API 调用。例如,我有一个数组 ['London', 'New York', 'Mexico', 'China', 'Tokyo']

我想使用开放天气 api 获取所有天气。我正在尝试使用 promise.all。在渲染到前面之前,我需要返回所有数据,但是我的代码不起作用。

let cities = ['London', 'New York', 'Mexico', 'China', 'Tokyo'] 
let promisesArray = []
return new Promise(function(resolve, reject) {
    for(let i = 0; i < cities.length; i++) {

        let cities = ['London', 'New York', 'Mexico', 'China', 'Tokyo'] 
        let url = 'api.openweathermap.org/data/2.5/weather?q=' + cities[i]
        request(url, function(error, response, body){

            if (err) {
                reject(error);
            }

            var data = JSON.parse(body)
            var results = data.Search;
            promisesArray.push(resolve(results));
        });

    }
})

    Promise.all(promisesArray)
        .then(function(results) {

        })
        .catch(function(error) {

        })

【问题讨论】:

  • 为什么要使用 return ?如果在函数内部,代码中的 Promise.all 将不会运行。

标签: node.js api asynchronous promise request


【解决方案1】:

您有几件事混淆了,但这是正确的想法。您的 promiseArray 需要包含承诺,而不是数据。

所以你应该遍历你的城市,为每个城市创建一个承诺,在承诺调用 request 和当请求返回时调用 resolvearray.mapfor 循环更简洁。

这是一个模拟 request 函数的示例:

// fakes request
function request(url, cb) {
  setTimeout(() => cb(null, 200, `{"Search": "success for ${url}" }`), 200)
}


let cities = ['London', 'New York', 'Mexico', 'China', 'Tokyo']

// promisesArray will hold all the promises created in map()
let promisesArray = cities.map(city => {
  // make a new promise for each element of cities
  return new Promise((resolve, reject) => {
    let url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city
    request(url, function(error, response, body) {
      if (error) {
        reject(error);
      }
      var data = JSON.parse(body)
      var results = data.Search;
      // resolve once we have some data
      resolve(results);
    });
  })
})

Promise.all(promisesArray)
  .then(function(results) {
    console.log(results)
  })
  .catch(function(error) {
    console.log(error)
  })

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2010-12-30
    • 2014-04-13
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多