有条件地使用水线(帆.js)中的承诺创建新条目



我有一系列"产品"。如果数据库为空,我想将这些产品保存到数据库中,并且当所有数据库操作完成后,我想显示一条消息。

我无法使用蓝鸟承诺(使用 .all 或 .map)做到这一点。我能够通过返回 Product.create(products[0]) 来创建一个项目。我无法绕开它,我对承诺是新手。

这是我的帆.js项目的引导文件,但这个问题是关于如何使用蓝鸟承诺的。如何设法等待多个异步任务(创建 3 个产品)完成然后继续?

  products = [
    {
      barcode: 'ABC',
      description: 'seed1',
      price: 1
    },
    {
      barcode: 'DEF',
      description: 'seed2',
      price: 2
    },
    {
      barcode: 'GHI',
      description: 'seed3',
      price: 3
    }
  ];

  Product.count()
  .then(function(numProducts) {
    if (numProducts > 0) {
      // if database is not empty, do nothing
      console.log('Number of product records in db: ', numProducts);
    } else {
      // if database is empty, create seed data
      console.log('There are no product records in db.');
      // ???
      return Promise.map(function(product){
        return Product.create(product);
      });
    }
  })
  .then(function(input) {
    // q2) Also here how can decide to show proper message
    //console.log("No seed products created (no need, db already populated).");
    // vs
    console.log("Seed products created.");
  })
  .catch(function(err) {
    console.log("ERROR: Failed to create seed data.");
  });

通了...

  products = [
    {
      barcode: 'ABC',
      description: 'seed1',
      price: 1
    },
    {
      barcode: 'DEF',
      description: 'seed2',
      price: 2
    },
    {
      barcode: 'GHI',
      description: 'seed3',
      price: 3
    }
  ];

  Product.count()
  .then(function(numProducts) {
    //if (numProducts > 0) {
    if(false) {
      // if database is not empty, do nothing
      console.log('Number of product records in db: ', numProducts);
      return [];
    } else {
      // if database is empty, create seed data
      console.log('There are no product records in db.');
      return products;
    }
  })
  .map(function(product){
    console.log("Product created: ", product);
    return Product.create(product);
  })
  .then(function(input) {
    console.log("Seed production complete.");
  })
  .catch(function(err) {
    console.log("ERROR: Failed to create seed data.");
  });

相关内容

  • 没有找到相关文章

最新更新