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

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

我需要输出一长串货件及其跟踪状态/跟踪URL

如果我 运行 同步执行此操作,则可能需要很长时间。因此,如果我 运行 它是异步的,它应该更快,因为所有请求将同时 运行,然后 return 所有信息都完成后发送到前端。

所以我仍在学习 node 并使用 promises,但是到目前为止我已经做到了......但问题是 Promise.all 似乎永远不会执行。所以我不确定我是否正确地执行了 Promise 功能,还是我不知道 easyPost API?

是的,现在我只使用 2 个货件 ID,但它可以 运行 100 个或更多...

是否还有一种方法可以在检索货物时 return 使用跟踪器元素,这样我就不必为每个货物调用 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)
        })
      })
    }

您需要解决或拒绝承诺。如果您需要跟踪器元素,请获取并解决。


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