从没有任何异步知识的Node开始,想知道如何将数据作为回调的一部分推入数组。输出数组已声明,但在请求回调中对其进行引用时未定义。是否有一种简单的方法就可以将该变量传递到回调函数作用域中?
理想情况下,我想将每个请求的结果数组发回给调用方。
const request = require('request');
module.exports = {
apiRatingCall: function (input, callback) {
var output = []
for (var i = 0; i < input.length; i++) {
var options = {
url: 'someAPIURL' + '?longitude=' + input[i].longitude + '&latitude=' + input[i].latitude + '&name=' + input[i].name,
headers: {
'x-api-version': 2
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
output.push(info) // this is not working as ouput is undefined at this point
}
})
}
callback(output)
}
}
谢谢
我的回答在编程中可能不是很规范,这只是解决这个问题的唯一方法
module.exports = {
apiRatingCall: function (input, callback) {
var output = []
for (var i = 0; i < input.length; i++) {
var options = {
url: 'someAPIURL' + '?longitude=' + input[i].longitude + '&latitude=' + input[i].latitude + '&name=' + input[i].name,
headers: {
'x-api-version': 2
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
output.push(info) // this is not working as ouput is undefined at this point
}
})
}
setTimeout(function(){
callback(output)
},500)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句