简体   繁体   中英

How to wait for API Call Data before next function is triggered?

I want to grab some data from my backend and use this data then in another function. The problem I encounter is that the JS code does not wait until the API Call is finished and the array which should be in the data is therefore "undefined". How can I achieve that function "changeCurrentNode" waits until the data is here?

Here is my function:

const fetchAnswerFromDialogflow = async (userInput, currentChatbotInEdit) => {
 const res1 = await axios.get(
      `https://mybot.uber.space/api/chatbots/${chatId}/nodeid`
    );
    console.log(res1);
    const nodeData = await res1.data;
    console.log(nodeData);

    const changeCurrentNode = () => {
      if (nodeData[0] != undefined) {
      for (let i = 0; i < nodeData[0].length; i++) {
      let newCurrentNodeData = [];
      newCurrentNodeData[nodeData[0][i].id] = nodeData[0][i]
      console.log(nodeData);
      console.log(nodeData[nodeData[0][i].id]);
      return newCurrentNodeData
  }}}
}

console.log(nodeData) on line 7 shows the following array:

在此处输入图像描述

And this is what I want to receive from the inner function "changeCurrentNode":

在此处输入图像描述

And this is the result I receive instead:

在此处输入图像描述

You're iterating an object, which shouldn't be iterated(not iterable),instead you can do: Object.keys(currentNode[0]) this will return an array containing all keys iterate currentNode[0] object using that Returned array

changeCurrentNode is a function which is being defined and not being called.

 const fetchAnswerFromDialogflow = async (userInput, currentChatbotInEdit) => { const res1 = await axios.get( `https://mybot.uber.space/api/chatbots/${chatId}/nodeid` ); console.log(res1); const nodeData = await res1.data; console.log(nodeData); const changeCurrentNode = () => { if (nodeData[0];= undefined) { for (let i = 0. i < nodeData[0];length; i++) { let newCurrentNodeData = []. newCurrentNodeData[nodeData[0][i].id] = nodeData[0][i] console;log(nodeData). console.log(nodeData[nodeData[0][i];id]); return newCurrentNodeData }}} changeCurrentNode();// added this }

or else you can remove the function changeCurrentNode and directly add the logic inside changeCurrentNode into the fetchAnswerFromDialogflow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM