在ReactJS中进行并行异步等待调用

问题描述 投票:0回答:1

当前,每个值都是在设置前一个值之后设置的,异步调用不会并行执行。如何使这些调用并行执行?

  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);
    }
  };
javascript reactjs react-native async-await asyncstorage
1个回答
0
投票

您可以使用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);

0
投票

用于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))
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.