【发布时间】:2017-09-16 01:36:44
【问题描述】:
我将一个数组传递给async.each(),其中执行将通过if 条件,当进入else 语句时满足条件时,它将项目添加到数组中,执行将不等待shippo响应。它移动到下一行并将响应发送到服务器。
我注意到几秒钟后我们收到了来自shippo 的响应,所以我在else 块完成后放置了一个setTimeout() 函数,但即使在我的控制台中,消息'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
【问题讨论】:
-
回调的想法是在调用之后你什么都不做,然后在调用完成时执行回调函数。要停止执行,您在调用后根本没有任何代码。
标签: javascript node.js callback shippo