2016-12-05 39 views
1

我是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,但控制檯似乎永遠掛起。

+0

您正嘗試更改異步方法中的數據。他們以不同的方式。也許你應該在url請求的回調方法中加入「next(data)」方法。 –

回答

0

我相信你嘗試呼叫的URL請求作爲同步的方式,但結果的作品,如你所說,異步。

我相信這個庫可以很好的爲你:async

此外,你可以寫你的方法爲遞歸風格。但這不是一個好的做法。您應該將此方法更改爲立即調用,然後在回調帖子方法內傳遞faceAPI(data)方法。

0

for look的一個迭代就是這樣,它不會等到回調被解析後纔開始下一個。因此,在完成任何請求之前,可能會完成forloop並返回到next函數。

如果您對一個接一個地發生的調用沒問題,您可以將它們放在遞歸函數中,並在完成前一個請求後發出下一個請求。

var arr = Object.keys(data); // store the key names in an array 

emotionsAPI(0, data, faceAPI) 

function emotionsAPI(data, index, next) { 
    if(index < arr.length) { 
    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[arr[index]].anger = scores.anger; 
     } 
     emotionsAPI(data, ++index, next); 
    }) 
    } else { 
    next(data); 
    } 
} 

否則,如果你想仍然是同時提出的要求,我會建議尋找到Promises。具體爲Promise.all