简体   繁体   English

将 Promise.all 与 easyPost API 一起用于跟踪状态的多个请求

[英]using Promise.all with easyPost API for multiple requests for tracking status

I need to output a long list of shipments and their tracking Status/ tracking URL .我需要 output 一长串货物及其跟踪状态/跟踪URL

If I was running this synchronously then it may well take a very long time.如果我同步运行它,那么它可能需要很长时间。 So if I run it asynchronously it should be quicker as all the requests will run at the same time, then return all the information to the frontend when it's all done.因此,如果我异步运行它应该会更快,因为所有请求将同时运行,然后在全部完成后将所有信息返回到前端。

So I'm still learning in node and using promises, however I have got this so far... but the problem is that the Promise.all never seems to execute.所以我仍在学习节点并使用承诺,但是到目前为止我已经做到了......但问题是 Promise.all 似乎永远不会执行。 So I'm not sure if I'm doing the Promise function correctly or is it something I don't know about the easyPost API ?所以我不确定我是否正确地执行 Promise function 还是我不了解easyPost API

yes for now I'm just using 2 shipment Id's but it could run to 100's or more...是的,现在我只使用 2 个货件 ID,但它可能会运行到 100 个或更多...

also is there a way of returning a tracker element when retrieving a shipment, so that I don't have to do 2 calls for each shipment?还有一种方法可以在检索货件时返回跟踪器元素,这样我就不必为每批货件打 2 次电话了吗?

var promise = []
promise.push(getShipmentPromise('shp_xxxShipmentId'))
promise.push(getShipmentPromise('shp_xxxShipmentId2'))
Promise.all(promise)
   .then(response => {
      console.log('Sent - ' + req.method + req.originalUrl)
      console.log('promise.all complete.')
      // within an expressjs route
      res.json(batches)
   })
   .catch(err => {
      console.log(err)
   })        

    function getShipmentPromise (shipmentId) {
      return new Promise((resolve, reject) => {
        easyPostAPI.Shipment.retrieve(shipmentId).then(response => {
          console.log(response.created_at)
        })
      })
    }

You need to resolve or reject the promise.您需要解决或拒绝 promise。 If you need a tracker element, get that and then resolve.如果您需要一个跟踪器元素,请获取它然后解决。


function getShipmentPromise (shipmentId) {
      return new Promise((resolve, reject) => {
        easyPostAPI.Shipment.retrieve(shipmentId).then(response => {
          console.log(response.created_at)
          resolve(response)
        })
      })
}

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

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