需要节点异步解释

时间:2016-07-12 05:40:30

标签: node.js asynchronous

我无法理解下面的代码出了什么问题。我有一个名为importOrder的函数,它通过将给定对象转换为新的订单对象来导入订单。我想要做的是,对于给定对象中的每个产品(line_item),获取产品详细信息并添加到新订单对象(newOrder.products)。问题是数组总是空的。我知道这是一个常见的问题,但我只是不明白发生了什么(这是封闭的事情吗?)

这是定制的代码

'use strict';

var Promise = require('promise');
var Order = require('./models/order');
var shopifyAPI = require('shopify-node-api');
var config = require('config');

var orderImporter = {

  importOrderFromShopify: function (shopifyOrder) {

    return new Promise(function(fulfill, reject){
      var newOrder = new Order({
        external_id: shopifyOrder.name,
        status: 'Awaiting Fulfillment',
        date_created: shopifyOrder.created_at,
        subtotal_inc_tax: shopifyOrder.subtotal_price,
        tracking_number: "",
        order_source: "www",
        payment_method: "Credit Card",
        invoice_printed_at: null,
        packing_slip_printed_at: null,
        products: [],  // this is the array I would like to populate with product details fetched from shopify
        product_options: []
      });

      shopifyOrder.line_items.forEach(function(lineItem){
        var productId = lineItem.product_id;
        var product = {};
        (function(newOrder){
          loadProductImage(productId)
            .then(function(imageUrl){
              product.image = imageUrl;
              newOrder.products.push(product);
            }, function(error){
              console.log(error);
            });
        })(newOrder);
        });

      newOrder.save(function(error){
        if (error){
          reject(error);
        } else {
          fulfill(newOrder);
        }
      });

    });


    function loadProductImage(productId){

      return new Promise(function(fulfill, reject){
        var shopifyClient = new shopifyAPI({
          shop: config.get('shopify_config.shop'),
          shopify_api_key: 'xxxx',
          shopify_shared_secret: 'yyyyy',
          access_token: 'zzzzzzzz',
          verbose: false
        });

        shopifyClient.get('/admin/products/' + productId + '/images.json', function(error, data){

          if(error){
            reject(error);
          } else {
            fulfill(data.images[0].src);
          }
        });
      });

    }

  }
};

module.exports = orderImporter;

1 个答案:

答案 0 :(得分:0)

使用.map代替.forEach并返回承诺数组。然后等到所有承诺都以Promise.all解决。然后,您可以保存新订单并履行importOrderFromShopify承诺