【发布时间】: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