【发布时间】:2017-10-12 10:53:16
【问题描述】:
我的节点、js 模块中有一个名为 data 的对象:
{
"item_uuid": "77306c44-4175-4aee-866d-d8df89fa3ii9",
"accounts": [{
"accountid": "B15501",
"quantity": 1
},
{
"accountid": "S20000",
"quantity": 1
}]
}
我需要通过将 accountid 传递给 API 来使用国家代码填充帐户中的每个帐户,然后再传递整个数据以进行进一步处理。
所以我在帐户中循环每个帐户并执行以下操作:
data.accounts.forEach(function(account) {
var clientAPI = "http://0.0.0.0:3000/" + account.accountid + "/?fields=country";
request.get(clientAPI, function (err, response, body) {
if (err) {
console.log("Unable to get country code for " +
account.accountid + " : " + err.message);
} else {
var clientData = JSON.parse(body);
account.country_code = clientData.country
}
})
}
// once all accounts have got country code, perform insertion into database
processData(data);
不幸的是,对 clientAPI 的调用是异步的,它不会等待返回结果,因此当数据到达 processData 时,它仍然没有 country_code。
所以我在这里尝试瀑布:
var waterfall = require('async-waterfall');
waterfall([
function (callback) {
data.accounts.forEach(function(account) {
var clientAPI = "http://0.0.0.0:3000/" + account.accountid + "/?fields=country";
request.get(clientAPI, function (err, response, body) {
if (err) {
console.log("Unable to get country code for " + account.accountid + " : " + err.message);
} else {
var clientData = JSON.parse(body);
account.country_code = clientData.country
}
})
}
callback(null, data);
}
], function(err, data){
processData(data);
})
可惜还是不行,到了processData(data),还是没有country_code。
我在这里使用瀑布时缺少什么?在 processData(data) 之前,我还能做些什么来填充上面的 country_code?
我必须调用 API 来获取每个帐户的 country_code。
【问题讨论】:
标签: node.js