【问题标题】:Why using await is also giving a pending promise in my code?为什么使用 await 也会在我的代码中给出一个未决的承诺?
【发布时间】:2021-04-23 19:07:27
【问题描述】:

为什么即使在 getCart() 方法中使用 await 后,我仍然收到待处理的承诺?我的代码在概念上是否有问题?

请帮忙。谢谢!

class User {
  constructor(..., cart) {
      //...
      this.cart = cart; //{items: []}
  }

  getCart() {
    return (async () => {
        const products = this.cart.items.map(async (item) => {
            const product = await Products.getProductDetail(item.productId);    //this returns a promise.
            product.qty = item.qty;
            return product; //<pending> Promise
        });  
        console.log(products);  //<pending> Promise
        return products;  
    })();
  }
}

这里是函数调用:

exports.renderCart = (req, res, next) => {
    (async () => {
        const products = await req.user.getCart(); //req.user is a User class object, ignore it.
        console.log(products);  //pending promise :(
        res.render('shop/cart', { products, pageTitle: 'Cart'});
    })();
};

【问题讨论】:

  • getCart() 中你应该await products 的值。此外,您似乎应该使用Promise.all,因为它是一系列承诺。
  • 另外,getCartrenderCart 中的异步 IIFE 似乎完全没有必要。
  • 异步函数自动返回一个 Promise。可以从 awaiting 在另一个异步函数中访问返回值 with Promise.then

标签: javascript node.js express promise async-await


【解决方案1】:

products 在您的代码中是一组承诺。您需要等待他们全部使用Promise.all

这个问题可以用一些模型来演示

var fakeWait = x => new Promise(resolve => setTimeout(() => resolve(x), 1000));

function test(){
  const items = [1,2,3,4,5]

  const result = items.map( async x => await fakeWait(x));
  console.log(result); // list of unresolved promises
}

async function test2(){
  const items = [1,2,3,4,5]

  const result = await Promise.all(items.map( async x => await fakeWait(x)));
  console.log(result); // list of resolved values
}

test();
test2();

此外,您的 getCart 方法过于复杂 - 它不需要是 IIFE

getCart() {        
    const products = this.cart.items.map(async (item) => {
            const product = await Products.getProductDetail(item.productId);    //this returns a promise.
            product.qty = item.qty;
            return product; //<pending> Promise
    });  
    return Promise.all(products);          
}

然后简单地说:

const products = await req.user.getCart();

【讨论】:

  • 非常感谢@jamiec。你的回答帮助我解决了这个问题,也教会了我更多关于 Promises 的知识。祝你有美好的一天:)
  • @Mitanshu 很高兴我能帮上忙!
猜你喜欢
  • 2017-06-19
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
相关资源
最近更新 更多