【问题标题】:How to access results of shopify-node-api request outside callback function如何在回调函数之外访问 shopify-node-api 请求的结果
【发布时间】:2017-06-13 00:13:54
【问题描述】:

我正在构建 Shopify 应用,但在使用 shopify-node-api 模块时遇到了问题。这是我正在使用的代码:

collectProducts: ['storedProducts', function(results, callback) {

  const collected_products = results.storedProducts;

  for (var i = 0; i < collected_products.length; i++) {

    Shopify.post('/admin/collects.json', {
      "collect": {
        "product_id": collected_products[i].product_id,
        "collection_id": process.env.DAILY_COLLECTION
      }
    }, function(err, data, headers){
      collected_products[i].collect_id = data.collect.id;
    });
  }

  callback(null, collected_products);
}],

为了清楚起见,collectProducts 项目是异步函数的一部分。我正在尝试从对发布请求的响应中收集收集 ID,并更新 collected_products 中的 collect_id 值。问题是我似乎无法从 post 请求的回调函数内部访问 collected_products 数组。有没有办法 1. 简单地为 for 循环的每次迭代返回该值或 2. 从该回调函数中访问 collected_products 数组以存储这些值?

提前感谢您的任何回答!

【问题讨论】:

  • shopify.post 回调中collected_products 的值是多少,可以打印一下吗?
  • 它只是显示为未定义。上述用例中的具体错误类似于“无法访问未定义的属性'collect_id'”。
  • 首先,确保collect_id 属性存在于每个collected_products 数组中。您能告诉我 Shopify.post() 回调中的 collect_products 的确切 console.log 结果吗?
  • 是的,绝对是,它记录了两次——每次循环迭代一次。 [ { product_id: 10274628419, database_product_id: null, collect_id: null, title: 'Title', image: 'https://cdn.shopify.com/s/files/1/1954/3027/products/A_title.jpg?v=1494608775' }, { product_id: 10274666755, database_product_id: null, collect_id: null, title: 'Title', image: 'https://cdn.shopify.com/s/files/1/1954/3027/products/A_title.jpg?v=1494608968' } ]
  • 小更新 - 如果我将迭代索引分配给循环内的变量 (` const theIndex = i;) and use that to access the index instead it seems to work within the loop. So for example console.log(collected_products[theIndex].collect_id);` 输出正确的值在循环内,但它似乎没有在我需要的循环外更新 collected_products 数组。

标签: javascript arrays node.js shopify


【解决方案1】:

对于后来遇到此问题的任何人,我可以通过使用我已经用于应用程序其他部分的异步模块来解决问题。 mapSeries 函数完成了我想做的事情。

// Get storedProducts from previous async function
async.mapSeries(results.storedProducts, function(product, cb) {
  // Adding the new collect here
  Shopify.post('/admin/collects.json', {
    "collect": {
      "product_id": product.product_id,
      "collection_id": process.env.DAILY_COLLECTION
    }
  }, function(err, data, headers) {
      // Update the product object with the Shopify-generated collect id
      product.collect_id = data.collect.id
      // Add the result to the mapSeries array
      cb(err, product);
    });
  }, function(err, results) {
    // Pass the now updated mapSeries array to the next async function
    callback(err, results);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多