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



我正在使用 react-native firebase 将我的媒体保存到 firebase 中。我有一组网址需要保存在火力库中。为此,我使用 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函数:)

使用 .map 很好,所以你可以返回一个承诺数组,然后你可以等待它们的解决

在这种情况下,Promise.all 中的解析值将是你推送到数组中的值......即this.state.mediaPath

var completedMediaSurveysAnswers = [{}, {}, {}]; //object array of URLs and media types
var promises = completedMediaSurveysAnswers.map((i) => new Promise((resolve, reject) => {
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');
resolve(null); // so one failure doesn't stop the whole process
}, uploadedFile => {
// Success
this.setState({
mediaPath: uploadedFile.downloadURL
})
resolve(this.state.mediaPath)
});
} catch (error) {
console.log(error)
resolve(null); // so one failure doesn't stop the whole process
}
}));
//need to call this function after loop is done
Promise.all(promises).then(mediaArray => {
saveAnswers(mediaArray);
});

据我所知,我们可以像下面这样。

学习方式 :https://www.codegrepper.com/code-examples/javascript/wait+for+map+to+finish+javascript

在 .map(( 完成后执行操作:

var promises = testUserArray.map((item, index) => {
console.log('item', item)
})
await Promise.all(promises).then(() => {
console.log('Map Opration Successfully Completed')
})

示例应用:

import React, { useState } from 'react'
import { View, StatusBar, Text, Button } from 'react-native'
export default function App() {
const [testUserArray, setTestUserArray] = useState(testArray)
const _testMap = async () => {
var promises = testUserArray.map((item, index) => {
console.log('item', item)
})
await Promise.all(promises).then(() => {
console.log('Map Opration Successfully Completed')
})
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', }}>
<Button
title='Test .map()'
onPress={() => _testMap()}
/>
</View>
)
}
const testArray = [
{
"id": '1',
"name": 'User 1'
},
{
"id": '2',
"name": 'User 2'
},
{
"id": '3',
"name": 'User 3'
},
{
"id": '4',
"name": 'User 4'
},
{
"id": '5',
"name": 'User 5'
},
]

只需检查地图数组的长度并将其与地图键进行比较即可。

使用async await等待文件上传

var mediaArray = []; //array of success callbacks values
var completedMediaSurveysAnswers = [{}, {}, {}]; //object array of URLs and media types
completedMediaSurveysAnswers.map(async (i, key) => {
try {
const storage = firebase.storage();
const mRef = storage.ref('portal').child('Survey/Image/user/' + uuidv4() + 'media');
await 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)
});
if( key == (completedMediaSurveysAnswers.length - 1 ) ){
saveAnswers(mediaArray)
}
} catch (error) {
console.log(error)
}
})

我没有测试async await所以无论在哪里使用它。

相关内容

  • 没有找到相关文章

最新更新