繁体   English   中英

在获得回调函数的响应之前,如何停止执行流程?

[英]How do we the halt the execution flow, till we get the response from a callback function?

我正在将一个数组传递给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');
      }
 });

这是我的输出以及放置超时功能后的shippo响应

我强烈建议您查看有关AsyncFunction()async库文档。 无论您已成功完成请求还是发生错误,似乎都应该调用回调。

由于Shippo库使用'when'处理类似诺言的链接(在撰写本文时,我在GitHub上有一个开放的PR来将其弃用到更普通的诺言链接)。

使用'when'的结果是,要捕获错误,您将通过.then()两个函数,一个用于成功路径,另一个用于处理错误。 它会像这样工作:

shippo.track.get_status('usps', '1122334455667788')
      .then(function (results){
         // do stuff with your successful function call
      }, function (error) {
         // do stuff with the error you just received
      });

console.log('c')最后打印出来的原因是,在原始承诺解决从Shippo检索跟踪状态之前,它不会执行该行。

另外,通过在setTimeout()函数中调用callback() ,您仅将每次迭代的解析时间延迟了3秒钟,但不必保证您对shippo函数的调用成功或失败。

你应该调用callback()每个传递到函数的内部函数then() 因此,一旦收到结果,就可以解析async.each()调用的函数的实例。 通过处理这些函数内部的callback() ,可以正确处理成功和错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM