Rainer Winkler
Rainer Winkler

Reputation: 565

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:

enter image description here

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

enter image description here

And this is the result I receive instead:

enter image description here

Upvotes: 0

Views: 1253

Answers (2)

Rajesh Kumaran
Rajesh Kumaran

Reputation: 201

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

Upvotes: 1

Jad Al-Hamwi
Jad Al-Hamwi

Reputation: 169

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

Upvotes: 1

Related Questions