如何从promise.all内部返回数据

时间:2018-09-06 12:53:31

标签: node.js return

findCustomerOrders(customerId) {
    return APIService.getCustomerOrders(this, customerId)
      .then((data) =>  {
        data.map(order => {
          return Promise.all([APIService.getShippingAddress(this, order.id), APIService.getProducts(this,order.id), APIService.getCustomerById(this, customerId)])
          .then((returnedData)=>{
            return buildOrder(returnedData);
          });
      });
   });
  }

要返回数据的函数是

findCustomerOrders(1)
.then((final) =>{console.log(final)});

我必须返回由buildOrder函数返回的数据,由于Promise.all(),我无法取回数据,并且它显示的返回值为未定义。 buildOrder函数正确返回值,但问题在于上述代码块,也仅是return语句 请帮帮我。

4 个答案:

答案 0 :(得分:0)

不返回Promise.all()。相反,只需像这样在其末尾调用.then()

findCustomerOrders(customerId) {
return APIService.getCustomerOrders(this, customerId)
  .then((data) =>  {
    data.map(order => {
      Promise.all([APIService.getShippingAddress(this, order.id), APIService.getProducts(this,order.id), APIService.getCustomerById(this, customerId)]).then((returnedData) => {
        return buildOrder(returnedData);
      })
   });
 });
}

还有buildOrder(returnedData)是否被传递到其他地方?因为如果不是,那么您应该直接将其调用而不返回它。

答案 1 :(得分:0)

如果返回是要在调用buildOrder之后使用findCustomerOrders返回的数据,则可以.then。只要确保该函数返回一个Promise。

findCustomerOrders(1).then((data) => {
   // data should be what buildOrder resolve to.
})

data.map返回一个Promises数组,每个数组都将解析为buildOrder结果。因此,您也应该在此返回一个Promise:

findCustomerOrders(customerId) {
    return APIService.getCustomerOrders(this, customerId)
      .then((data) =>  {
        return Promise.all(data.map(order => {
          return Promise.all([APIService.getShippingAddress(this, order.id), APIService.getProducts(this,order.id), APIService.getCustomerById(this, customerId)])
          .then((returnedData)=>{
            return buildOrder(returnedData);
          });
      }));
   });
  }

答案 2 :(得分:0)

如果您使用的是promise.all,那么函数会有多个输出,因此您应该将所有输出变量写入数组。

findCustomerOrders(customerId) {
return APIService.getCustomerOrders(this, customerId)
  .then((data) =>  {
    data.map(order => {
      return Promise.all([APIService.getShippingAddress(this, order.id), APIService.getProducts(this,order.id), APIService.getCustomerById(this, customerId)])
      .then(([result1, result2, result3])=>{
        return buildOrder([result1, result2, result3]);
      });
  });
   });
  }

这可能是可行的,如果值未定义,它将不会给您未定义的值。

答案 3 :(得分:0)

我从导师那里得到了解决方案:

findCustomerOrders(customerId) {
    return APIService.getCustomerOrders(this, customerId)
      .then(orders => orders.map(order => Promise.all([APIService.getShippingAddress(this, order.id), APIService.getProducts(this, order.id), APIService.getCustomerById(this, customerId)])
        .then((returnedData) => {
          return buildOrder(order);
        })))
      .then(promises => Promise.all(promises));
  }