You need to enable JavaScript to run this app. 在Node.js中如何通过Promise向数组对象传值?Express调用Shopify API数组为空如何解决
优惠活动
大模型
产品
解决方案
定价
更多

在Node.js中如何通过Promise向数组对象传值?Express调用Shopify API数组为空如何解决

问题原因
  • 核心是JavaScript异步执行时序问题:client.product.fetchAll() 是异步网络请求接口,返回Promise对象,.then() 中的回调逻辑只有等Shopify接口返回数据后才会执行。
  • 你写的打印数组长度、返回数组的代码都是同步逻辑,会在接口请求还未完成时就提前执行,此时productList还没有被推入任何数据,自然长度为0。
修复方案

推荐用async/await改写异步逻辑,代码可读性更高,修改后的代码如下:

const fetch = require("node-fetch");
const Product = require("./Product");
const client = Client.buildClient(
  {
    domain: "storename.myshopify.com",
    storefrontAccessToken: "token",
  },
  fetch
);
const ProductList = class {
  // 方法加async标识
  async getProductList() {
    var productList = [];
    // 等待接口请求返回结果
    const products = await client.product.fetchAll();
    products.forEach((product) => {
      const p = new Product(
        product.availableForSale,
        product.createdAt,
        product.description,
        product.id,
        product.images,
        product.options,
        product.productType,
        product.publishedAt,
        product.title,
        product.variants
      );
      p.printProduct();
      productList.push(p);
    });
    console.log("size:" + productList.length);
    return productList;
  }
};

module.exports = ProductList;

调用注意事项

因为getProductList加了async标识后会默认返回Promise对象,你调用这个方法的时候需要用await或者.then()才能拿到正确的产品数组:

// 调用示例
const productListIns = new ProductList();
// 方式1:await调用(需要放在async函数内)
const list = await productListIns.getProductList();
console.log(list);

// 方式2:.then调用
productListIns.getProductList().then(list => {
  console.log(list);
})

内容的提问来源于stack exchange,提问作者Nhan Le

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 07:15:04