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

Firebase multiple async requests returned via Promises

我有一个 Firebase 函数,它试图获取一组 UID 和 return 一组用户对象。我正在尝试使用 Promise.all() 到 return 所有异步结果,但我得到一个空数组 returned。然而,事后我得到了注销的结果。

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() 启动的异步工作完成。另请注意,您实际上并没有将 promises 推入该数组。您正在推动普通的旧 JavaScript 对象。您需要将实际的承诺推送到数组中,并且您需要在不必等待其他承诺解决的情况下执行此操作。它应该是这样的:

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

}

请注意,promise 会立即被推入 promises 数组,并且它将使用 then 回调返回的 userData 对象进行解析。