You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行get_cart_products代码始终返回Promise { <pending> }的技术咨询

问题排查与解决方案

原因分析

你看到Promise { <pending> }是因为直接调用返回Promise的函数但未等待其完成,同时你的代码存在冗余的Promise包装——async函数本身就会返回Promise,不需要再手动套一层new Promise。

代码优化

先简化冗余的Promise包装,让代码更简洁合规:

get_cart_products: async (user_id) => {
  return db.get().collection(collection.CART_COLLECTION)
    .find({ user_id: objectId(user_id) })
    .toArray();
}

注:这里的await可省略,因为toArray()本身返回Promise,async函数会自动将其作为返回值;保留await也不影响逻辑,仅提升可读性。

正确调用方式

要获取实际产品数据,必须等待Promise完成,两种方式任选其一:

方式1:在async函数中用await

async function fetchCart(userId) {
  try {
    const cartProducts = await get_cart_products(userId);
    console.log(cartProducts); // 此处输出实际产品数组
  } catch (err) {
    console.error('获取购物车数据失败:', err);
  }
}

fetchCart('目标用户ID');

方式2:用.then()/.catch()处理Promise

get_cart_products('目标用户ID')
  .then(cartProducts => {
    console.log(cartProducts); // 此处输出实际产品数组
  })
  .catch(err => {
    console.error('获取购物车数据失败:', err);
  });

额外注意事项

  • 确认objectId是正确导入的合法函数(比如MongoDB的ObjectId),否则会导致查询条件失效,返回空数组或报错。
  • 检查db.get()是否正确返回数据库连接实例,避免因连接异常导致Promise长期处于pending状态。

内容的提问来源于stack exchange,提问作者labeeba anu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 02:54:25