Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making parallel async await calls in ReactJS

Currently each of the value is set after setting the previous value, the async calls are not executed in parrallel. How do I make these calls execute in parallel?

  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);
    }
  };
like image 637
Rohit Prasad Avatar asked Dec 08 '22 10:12

Rohit Prasad


2 Answers

You can use 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);

Or if you like to turn such thing into mapping monstrosity as recommended in the answers there you go...

const params = ['@branch', '@sem', '@roll'];
const defaultValues = [0, 1, 1];

const [index, semester, roll] = await Promise.all(
  params.map(AsyncStorage.getItem))
  .then((values) => values.map((pr, index) => JSON.parse(pr) || defaultValues[index]));

setIndex(index);
setSemester(semester);
setRollNo(roll);
like image 80
Józef Podlecki Avatar answered Dec 20 '22 01:12

Józef Podlecki


To execute several promises in parallel you need organize them as array and execute unsing Promise.all:

  const [index, setIndex] = useState(0);
  const [roll, setRollNo] = useState(1);
  const [sem, setSemester] = useState(1);

  useEffect(() => {
    getMyValue();
  }, []);

  const getMyValue = async () => {
    try {
      const itemsArr = ['@branch', '@sem', '@roll']
      const result = await Promise.all(promisesArr.map(item => AsyncStorage.getItem(item)))
      setIndex(JSON.parse(result[0]) || 0);
      setSemester(JSON.parse(result[1]) || 1);
      setRollNo(JSON.parse(result[2]) || 1);
    } catch (e) {
      //  console.log(e);
    }
  };
like image 30
elvira.genkel Avatar answered Dec 20 '22 02:12

elvira.genkel