我应该使用Promise来解决这个问题吗?

时间:2017-01-22 16:26:08

标签: javascript node.js promise es6-promise

我正在从网站请求项目,我需要检查主题的描述是否包含“purchsed”字样,然后才将其保存到数据库。

所以,当我做某事时,请说谎:

List<List<string[]>> objects

但它不起作用(项目在任何情况下都保存),因为在IF语句(isPurchased)中提供的函数返回undefined(因为异步节点行为,我认为)。

所以,我写了Promise notPurchased:

  MATERIAL  "STEEL"    TYPE "Steel"    WEIGHTPERVOLUME 7833.414
  MATERIAL  "STEEL"    SYMTYPE "Isotropic"  E 2.038902E+10  
  MATERIAL  "STEEL"  FY 3.515348E+07  FU 4.569952E+07 
  MATERIAL  "STEEL"  HYSTYPE "Kinematic"  SSTYPE "Simple"  


  MATERIAL  "CONC"    TYPE "Concrete"    WEIGHTPERVOLUME 2402.616
  MATERIAL  "CONC"    SYMTYPE "Isotropic"  E 2.531051E+09  U 0.2
  MATERIAL  "CONC"    FC 2812279
  MATERIAL  "CONC"  HYSTYPE "Concrete"  ENERGYDEGFACT 0


  MATERIAL  "OTHER"    TYPE "Other"    WEIGHTPERVOLUME 7833.414
  MATERIAL  "OTHER"    SYMTYPE "Isotropic"  E 2.038902E+10
  MATERIAL  "OTHER"  DESIGNTYPE "OTHER"  
  MATERIAL  "OTHER"  HYSTYPE "Elastic"  IOTENSION 0.01
  MATERIAL  "OTHER"  STRAIN -1 STRESS -1 
  MATERIAL  "OTHER"  STRAIN 0 STRESS 0 POINTID "A"  
  MATERIAL  "OTHER"  STRAIN 1 STRESS 1 

然后在forEach循环中使用此承诺:

items.forEach(function(item) {
  if(!isPurchased)
    saveToDb(item)
}

这是一个很好的方法吗?我对NodeJS没有足够的经验,在我看来,为简单的bool函数定义一个承诺似乎有点棘手。

1 个答案:

答案 0 :(得分:0)

嗯,你可以做的是循环查找db中没有的项目,然后用Promise.all插入所有项目。 会是这样的:

const itemsNotSaved = items.filter((item) => {
       //Check if item is in db already.
       //If it is, return false, if not, true
});

const itemsPromises = itemsNotSaved.map((item) => {
  //Create a new promise for inserting item
});

//Execute every Promise
Promise.all(itemsPromises)
.then((items) => {
 //No errors, items have been inserted in the database
})
.catch((error) => {
 //console.log(error);
})