gpt4 book ai didi

javascript - 如何在执行map()循环后调用函数

转载 作者:行者123 更新时间:2023-11-28 16:58:21 24 4
gpt4 key购买 nike

我正在使用react-native firebase 将我的媒体保存到firebase 中。我有一组需要保存在 firebase 中的 URL。为此,我使用 map() 来一一保存。保存后,我将成功 URL 推送到数组中。我需要用这个数组作为参数来调用一个函数。所以我需要在数组完成后调用这个函数。我进行了很多搜索,但没有找到此任务的良好解释。谁能帮我。谢谢。

var mediaArray = []; //array of success callbacks values
var completedMediaSurveysAnswers = [{}, {}, {}]; //object array of URLs and media types
completedMediaSurveysAnswers.map((i) => {
try {
const storage = firebase.storage();
const mRef = storage.ref('portal').child('Survey/Image/user/' + uuidv4() + 'media');
mRef.putFile(i.urlPath, {
contentType: i.mediaType
})
.on('state_changed', snapshot => {},
err => {
console.log('Failed to upload file to firebase storage')
},
uploadedFile => {
// Success
this.setState({
mediaPath: uploadedFile.downloadURL
})
mediaArray.push(this.state.mediaPath)
});
} catch (error) {
console.log(error)
}
})

//need to call this function after loop is done
saveAnswers(mediaArray)

最佳答案

您可以使用 Promise 或 async/await 来处理所有类型的情况,如下所示:

var mediaArray = [];
var completedMediaSurveysAnswers = [{}, {}, {}];

async function handleYourTask() {
await completedMediaSurveysAnswers.map((i) => {
try {
const storage = firebase.storage();
const mRef = storage.ref('portal').child('Survey/Image/user/' + uuidv4() + 'media');
mRef.putFile(i.urlPath, {
contentType: i.mediaType
})
.on('state_changed', snapshot => {},
err => {
console.log('Failed to upload file to firebase storage')
},
uploadedFile => {
// Success
this.setState({
mediaPath: uploadedFile.downloadURL
})
mediaArray.push(this.state.mediaPath)
});
} catch (error) {
console.log(error)
}
})

await saveAnswers(mediaArray);
}

然后你可以在任何你想要的地方调用handleYourTask函数:)

关于javascript - 如何在执行map()循环后调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com