每个then()应该在使用Promises时返回一个值或throw

时间:2018-02-12 16:16:12

标签: javascript node.js

我有一些异步方法需要在从请求返回之前等待完成。我正在使用Promises,但我一直收到错误:

Each then() should return a value or throw // promise/always-return

为什么这样开心?这是我的代码:

router.get('/account', function(req, res) {
  var id = req.user.uid
  var myProfile = {}
  var profilePromise = new Promise(function(resolve, reject) {
    var userRef = firebase.db.collection('users').doc(id)
    userRef.get()
      .then(doc => { // Error occurs on this line
        if (doc.exists) {
          var profile = doc.data()
          profile.id = doc.id
          myProfile = profile
          resolve()
        } else {
          reject(Error("Profile doesn't exist"))
        }
      })
      .catch(error => {
        reject(error)
      })
  })
  // More promises further on, which I wait for
})

4 个答案:

答案 0 :(得分:9)

避开Promise constructor antipattern!如果您不打电话给{{ran}} 但是返回一个值,那么您将获得resolve的内容。 return方法应该用于chaining, not just subscribing

then

答案 1 :(得分:2)

firebase.db.collection('users').doc(id)返回promise本身的情况下,请检查firebase代码段为here以获取node-js。

如果您有多个承诺,并且需要逐个调用它们,请使用Promises chaining

请检查此article这对您有帮助。

在您的案例中使用以下代码

          router.get('/account', function(req, res) {

            var id = req.user.uid;
            var myProfile = {};

            var userRef = firebase.db.collection('users').doc(id)

            userRef.get()
            .then(doc =>  {

                if (!doc || !doc.exists) {
                   throw new Error("Profile doesn't exist")
                }

                var profile = doc.data();
                profile.id = doc.id;
                myProfile = profile;

               return myProfile;

            })
            .catch(error => {
              console.log('error', error);
            })

          })

如果您有多个承诺并且您希望一次执行它们,请使用Promise.all。

Promise.all(iterable)方法返回一个Promise,它在iterable参数中的所有promise已经解析或者iterable参数不包含promise时解析。它拒绝承认拒绝的第一个承诺。

例如:

  var promise1 =  new Promise((resolve, reject) => {
    setTimeout(resolve, 100, 'foo1');
  });
  var promise2 =  new Promise((resolve, reject) => {
    setTimeout(resolve, 100, 'foo2');
  });
  var promise3 =  new Promise((resolve, reject) => {
    setTimeout(resolve, 100, 'foo3');
  });

  Promise.all([promise1, promise2, promise3])
  .then(result =>  console.log(result))
  //result [foo1, foo2, foo3] 

希望这会对你有所帮助!!

答案 2 :(得分:1)

then()

的末尾添加
return null

就是这样。

Each then() should return a value or throw Firebase cloud functions

答案 3 :(得分:0)

如果您无法解决此问题,但仍想运行您的代码...

open   : eslintrc.json file (search from project root directory)
search : 'promise/always-return'
change : Case 1: if (existing value is 2) => change to 1
         Case 2: else if(existing value is "error" => change to "warn")

这将使该错误成为警告,但请务必谨慎...还应在编辑器中使用eslint plungin来提醒良好做法。否则,您将不会收到任何与承诺/总是返回有关的警告。

如果您的搜索中出现多个eslintrc.json,还请确保找到正确的

相关问题