Search code examples
reactjsapiasync-awaitdialogflow-esuse-effect

How can I make sure that function 1 ends before function 2 starts within useeffect hook?


I created a chatbot and want to initiate two Dialogflow API calls within a useEffect Hook. Function 1 and function 2 are both async api calls. The wanted result is that it first finishes function 1 and then starts with function 2, but currently function 2 returns the value faster than function 1.

Do you have any idea how I can tell function 2 to wait until function 1 returns a value?

useEffect(
    () => {
      createChatSessionId();
      fetchEventAnswerFromDialogflow("Startevent" + chatId, chatId); // function 1
      fetchEventAnswerFromDialogflow("Frageevent1", chatId); // function 2
    }, // eslint-disable-next-line
    []
  );

Solution

  • API Calls are asynchronous. When the compiler hits an async statement, it doesnt wait for it to finish, instead calls next statement.

    Option one, (Using .then block) :-

      useEffect(
        () => {
          createChatSessionId();
          fetchEventAnswerFromDialogflow("Startevent" + chatId, chatId).then(rep=>{
          fetchEventAnswerFromDialogflow("Frageevent1", chatId);})
            .catch(err){
              console.log(err)
             }
        }, // eslint-disable-next-line
        []
      );
    

    Option two - As per ES6 using async await. I'd suggest not to make useEffect callback as async, instead make a new async function inside useEffect and call that.

    useEffect(
        () => {
          createChatSessionId();
          const getData = async() =>{
             await fetchEventAnswerFromDialogflow("Startevent" + chatId, chatId);
             await fetchEventAnswerFromDialogflow("Frageevent1", chatId);  //Can remove await 
                 //here, depending upon usecase
          }
          getData();
        }, // eslint-disable-next-line
        []
      );