Firebase通过Promises返回的多个异步请求

时间:2019-05-29 16:05:01

标签: javascript firebase firebase-realtime-database es6-promise

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

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)

1 个答案:

答案 0 :(得分:2)

/usr/share/nginx/html始终返回一个空数组。在将值推入数组之前,无法确保由fetchUserObjects开始的异步工作已完成。还要注意,您实际上并没有将promise放入该数组中。您正在推送普通的旧JavaScript对象。您需要将实际的Promise推送到数组中,而无需等待其他Promise解析就可以做到。而是这样的样子:

once()

请注意,一个诺言将立即推送到promises数组中,它将使用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对象来解决。