我將一個數組傳遞給async.each()
,執行過程將通過if
條件,當條件滿足時將條目添加到數組中,當進入else
語句時,執行不會等待shippo響應。它移動到下一行並將響應發送到服務器。我們如何暫停執行流程,直到獲得回調函數的響應?
我注意到,我們的幾秒鐘後正從shippo
的反應,所以我放在一個setTimeout()
功能else
塊完成後,但即使在我的控制檯消息'c'
將打印最後。我非常困惑與回調,他們將如何工作。除了獲得shippo
的響應之外,還有其他方法可以阻止執行流程。
var async = require('async');
import each from 'async/each';
async.each(trackingnumbers, function (value, callback) {
value['TrackingNo'] = parseInt(value['TrackingNo']);
value['Provider'] = value['Provider'].toLowerCase();
if (value['Provider'] == "domestic") {
items.push({ 'TrackingNo': value['TrackingNo'], 'Provider': value['Provider'], 'Status': 'Completed' });
console.log('a');
}
else {
console.log('b');
shippo.track.get_status(value['Provider'], value['TrackingNo']).then(function (status) {
console.log('c');
items.push({ 'TrackingNo': value['TrackingNo'], 'Provider': value['Provider'], 'Status': status.tracking_status });
}, functionconsole.log('d'); (err) {
console.log("There was an error retrieving tracking information: %s",+ err);
callback('There was an error retrieving tracking information:');
//
});
console.log('d');
e }
console.log('e');
setTimeout(function(){
callback();
},3000);
}, function (err) {
if (err) {
console.log('error occured ' + '|' + err);
}
else {
console.log(items);
res.setHeader("Access-Control-Allow-Origin", "*");
res.send(items).status('200');
}
});
Here is my output along with the shippo response after we placed an timeout function
帶有回調的想法是,您在完成調用後不做任何事情,然後在調用完成時執行回調函數。爲了停止執行,您只需在調用後沒有任何代碼。 – Archer