【问题标题】:Passing secondary data to my second callback function将辅助数据传递给我的第二个回调函数
【发布时间】:2020-01-30 06:16:31
【问题描述】:

我想在我的第二个回调中使用变量 intermediateData 但我不知道如何在我目前的情况下将它传递给那里。有人知道怎么做吗?

   const unsubscribe = firebase
     .locations()
     .once('value')
     .then(async snapshot => {
       const promises = []
       const intermediateData = snapshot.val()

       snapshot.forEach(element => {
         promises.push(firebase.user(element.key).once('value'))
       })

       return Promise.all(promises)
     })
     .then(snapshots => {
       const userInformation = []

       snapshots.forEach(userSnapshot => {
         if (userSnapshot.exists()) {
           userInformation.push({
             userId: 1,
             name: userSnapshot.val().username
           })
         }
       })
     })

   return () => unsubscribe
 }, [firebase, setSnackbarState, userId]) ```

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database react-hooks


    【解决方案1】:

    您可以返回一个包含Promise.all 结果和intermediateData 的对象

    const unsubscribe = firebase
      .locations()
      .once('value')
      .then(async snapshot => {
          const promises = []
          const intermediateData = snapshot.val()
    
          snapshot.forEach(element => {
            promises.push(firebase.user(element.key).once('value'))
          })
    
          return Promise.all(promises).then(snapshots => ({snapshots, intermediateData})
                                                          // ^^ return object
          })
        .then(({snapshots, intermediateData}) => {
               // ^^^ destructure returned object
          const userInformation = []
    
          snapshots.forEach(userSnapshot => {
            if (userSnapshot.exists()) {
              userInformation.push({
                userId: 1,
                name: userSnapshot.val().username
              })
            }
          })
        })
    

    【讨论】:

      【解决方案2】:

      把它放在外面的封盖里:

      let intermediateData;
      const unsubscribe = firebase
       .locations()
       .once('value')
       .then(async snapshot => {
         const promises = []
         intermediateData = snapshot.val()
      
         snapshot.forEach(element => {
           promises.push(firebase.user(element.key).once('value'))
         })
      
         return Promise.all(promises)
       })
       .then(snapshots => {
         //
         // Now you can access intermediateData here
         //
         // ...
       })
      

      【讨论】:

      • 这行得通!我更喜欢其他答案,因为这样做对我来说似乎更好。不过感谢您的帮助!
      猜你喜欢
      • 1970-01-01
      • 2013-01-16
      • 2021-09-22
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多