我想在第二次回调中使用变量 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]) ```
您可以返回一个包含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
})
}
})
})
把它放在外闭合中:
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
//
// ...
})