Firebase通过Promises返回的多个异步请求 [英] Firebase multiple async requests returned via Promises

查看:48
本文介绍了Firebase通过Promises返回的多个异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Firebase函数,它试图获取一个UID数组并返回一个用户对象数组。我正在尝试使用 Promise.all()返回所有异步结果,但返回的是空数组。但是,我是在事后获得注销结果。

I have a Firebase function that is attempting to take an array of UIDs and return an array of User Objects. I am trying to use Promise.all() to return all of the async results, but I am getting an empty array returned. I am, however, getting the logged out results after the fact.

const fetchUserObjects = function(uids){
  let promises = []
  uids.forEach((uid) => {
    admin.database().ref(`/users/${uid}`).once("value")
    .then(function(dataSnapshot) {
      const userDataAll = dataSnapshot.val()
      const userData = {}
      userData.id = userDataAll.id
      userData.username = userDataAll.username
      userData.first = userDataAll.first
      userData.last = userDataAll.last

      promises.push(userData)
      console.log(userData)
    })
    .catch((error) => {
      // Re-throwing the error as an HttpsError so that the client gets the error details.
      throw new functions.https.HttpsError('unknown', error.message, error);
    });
  })

  return Promise.all(promises);

}

return fetchUserObjects(uids)


推荐答案

fetchUserObjects 始终返回一个空数组。在将值推入数组之前,没有什么能确保由 once()开始的异步工作是完整的。另请注意,您实际上并没有将诺言推入该数组。您正在推送普通的旧JavaScript对象。您需要将实际的Promise推送到数组中,而无需等待其他Promise解析就可以做到。而是这样的样子:

fetchUserObjects is always returning an empty array. Nothing is ensuring that the async work started by once() is copmlete before you push values into the array. Also notice that you're not actually pushing promises into that array. You're pushing plain old JavaScript objects. You need to push actual promises into the array instead, and you need to do it without having to wait for other promises to resolve. Here's what it should look like instead:

const fetchUserObjects = function(uids){
  let promises = []
  uids.forEach((uid) => {
    const promise = admin.database().ref(`/users/${uid}`).once("value")
    .then(function(dataSnapshot) {
      const userDataAll = dataSnapshot.val()
      const userData = {}
      userData.id = userDataAll.id
      userData.username = userDataAll.username
      userData.first = userDataAll.first
      userData.last = userDataAll.last

      console.log(userData)
      return userData
    })
    .catch((error) => {
      // Re-throwing the error as an HttpsError so that the client gets the error details.
      throw new functions.https.HttpsError('unknown', error.message, error);
    });

    promises.push(promise)

  })

  return Promise.all(promises);

}

请注意,诺言立即被推入诺言数组,它将使用 userData 对象解析,该对象由 then 回调返回。

Notice that a promise is immediately pushed into the promises array, and it will resolve with a userData object that was returned by the then callback.

这篇关于Firebase通过Promises返回的多个异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆