然后不执行NodeJS Promise

时间:2018-08-29 14:01:50

标签: node.js promise

我需要一些帮助。这是我第一次尝试诺言。 这是我的诺言代码:

exports.deleteATarget = (req, res) => {
  deleteUniversRefInTarget(req.params.universName, req.params.targetName)
    .then((response) => {
      console.log('Fin du traitement de la promesse')
      if (response === 'deleteTarget') {
        Target.findOneAndDelete({ name: req.params.targetName, univers: req.params.universName },
          (err, target) => {
            if (err) {
              res.send(err)
            }
            res.json({ message: `Target ${target.name} isn't used in any univers, so we deleted it` })
          })
      } else {
        res.json({ message: `Target ${req.params.targetName} no longer used in ${req.params.universName} univers` })
      }
    })
    .catch((error) => {
      res.send(error)
    })
}

我在这里称呼这个诺言

import json

d = '{ "@context": "http://schema.org", "@type": "Product", "name":"Men\'s Slippers Brief Design Rivet Decor All Match Fashion Wearable Shoes", "image":"", "description": "Material:Faux Leather", "brand":{ "@type": "Thing", "name": "" }, "aggregateRating": { "@type": "AggregateRating", "ratingValue": "5", "reviewCount": "1" }, "offers": { "@type": "Offer", "availability": "http://schema.org/InStock", "price": "10.99", "priceCurrency": "USD" } }'
data = json.loads(d)
print(data['aggregateRating']['reviewCount']) #1
print(data['aggregateRating']['ratingValue']) #5

在控制台中,我可以看到: 删除deleteUniversRefInTarget 但不是承诺的性格

所以...你知道我在做什么不好吗?

2 个答案:

答案 0 :(得分:0)

我不确定我是否了解所有内容,但这是有关此反模式的新代码: ```

const deleteTargetOrDerefUniversInTarget = (universName, targetName) => {
  const promis = new Promise((resolve, reject) => {
    Target.findOne({ name: targetName, univers: universName })
      .then((target) => {
        if (target === null) {
          reject(TypeError(`Invalid univers'n name ${universName} or target's name ${targetName}`))
        } else if (target.univers.length === 1) {
          resolve({ action: 'deleteTarget', target })
        } else {
          resolve({ action: 'dereferencedUnivers', target })
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
  return promis
}

exports.deleteATarget = (req, res) => {
  deleteTargetOrDerefUniversInTarget(req.params.universName, req.params.targetName)
    .then((response) => {
      if (response.action === 'deleteTarget') {
        Target.findOneAndDelete({ name: response.target.name, univers: req.params.universName })
          .then((target) => {
            res.json({ message: `Target ${target.name} isn't used in any univers, so we deleted it` })
          })
          .catch((err) => {
            res.status(err.status).json(err)
          })
      } else {
        response.target.univers.splice(response.target.univers.indexOf(req.params.universName), 1)
        response.target.save()
        res.json({ message: `Target ${response.target.name} no longer used in ${req.params.universName} univers` })
      }
    })
    .catch((error) => {
      res.send(error)
    })
}

``` 在此新代码中,不再有exec调用。 第一个承诺只是发回一个操作来执行呼叫者管理的操作。

答案 1 :(得分:-1)

好吧,当我将猫鼬查询(findOneAndUpdate)转换为promise时,听起来要好得多: `

const deleteUniversRefInTarget = (universName, targetName) => {
  console.log('Appel de deleteUniversRefInTarget')
  const promis = new Promise((resolve, reject) => {
    Target.findOneAndUpdate({ univers: universName, name: targetName })
      .exec()
      .then((target) =>{
        console.log('Entrée dans la promesse')
        if (target === null) {
          reject(TypeError(`Invalid univers'n name ${universName}`))
        } else {  
          if (target.univers.length === 1) {
            resolve('deleteTarget')
          } else {
            target.univers.splice(target.univers.indexOf(universName), 1)
            resolve('dereferencedUnivers')
          }
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
  return promis
}

`

区别主要是.exec()部分。 我认为我们可以说这是解决问题的方法,即使我不确定这是否是正确的方法。