当前,每个值都是在设置前一个值之后设置的,异步调用不会并行执行。如何使这些调用并行执行?
const [index, setIndex] = useState(0);
const [roll, setRollNo] = useState(1);
const [sem, setSemester] = useState(1);
useEffect(() => {
getMyValue();
}, []);
const getMyValue = async () => {
try {
setIndex(JSON.parse(await AsyncStorage.getItem('@branch')) || 0);
setSemester(JSON.parse(await AsyncStorage.getItem('@sem')) || 1);
setRollNo(JSON.parse(await AsyncStorage.getItem('@roll')) || 1);
} catch (e) {
// console.log(e);
}
};
您可以使用Promise.all
const [index, semester, roll] = await Promise.all([
AsyncStorage.getItem('@branch'),
AsyncStorage.getItem('@sem'),
AsyncStorage.getItem('@roll')]);
setIndex(JSON.parse(index) || 0);
setSemester(JSON.parse(semester) || 1);
setRollNo(JSON.parse(roll) || 1);
用于await of ...
const response = []
const jobs = ["@branch", "@sem", "@roll"]
for await (item of jobs) {
const res = await AsyncStorage.getItem(item);
response.push({
type: item,
res
})
}
response.forEach(res => {
if (item === "@branch") {
setIndex(JSON.parse(res))
} else if (item === "@semester") {
setSemester(JSON.parse(res))
} else if (item === "@roll") {
setRollNo(JSON.parse(res))
}
})