Each then() should return a value or throw when using Promises

前端 未结 4 1706
粉色の甜心
粉色の甜心 2020-12-05 23:12

I have a few async methods that I need to wait for completion before I return from the request. I\'m using Promises, but I keep getting the error:

Each then(         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 00:13

    In your case firebase.db.collection('users').doc(id) returning promise itself, please check firebase snippet to here for node-js.

    If you have multiple promises and you need to call them one by one then use Promises chaining.

    Please check this article this will help you.

    Use following code in your case,

              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);
                })
    
              })
    

    And use Promise.all if you have multiple promises and you want's to execute them in once.

    The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

    For example:

      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] 
    

    Hopes this will help you !!

提交回复
热议问题