我是Node的新手,並且試圖在API調用的for循環中追加數據,但卻遇到了Node異步性質的挑戰。for循環後的Node.js回調
function emotionsAPI(data, next){
for(var url in data) {
if(data.hasOwnProperty(url)) {
request({
method: 'POST',
url: 'https://api.projectoxford.ai/emotion/v1.0/recognize',
headers: {
"Content-Type": 'application/json',
"Ocp-Apim-Subscription-Key": keys.emotion_key
},
body: "{\"url\" : \"" + url + "\"}"
}, function (error, response, body){
var emotions = JSON.parse(body)
if (emotions.length > 0){
var scores = emotions[0].scores;
console.log("scores found");
console.log(scores.anger);
data[url].anger = scores.anger;
}
})
}
}
next(data);
}
function faceAPI(data){
console.log("HELP");
console.log(data);
}
emotionsAPI(data, faceAPI);
faceAPI函數中的console.log正確地打印到控制檯,但未反映for循環應該做出的更改。我嘗試使用async.forEachOf,但控制檯似乎永遠掛起。
您正嘗試更改異步方法中的數據。他們以不同的方式。也許你應該在url請求的回調方法中加入「next(data)」方法。 –