简体   繁体   English

如何在触发下一个 function 之前等待 API 调用数据?

[英]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.我想从我的后端获取一些数据并在另一个 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".我遇到的问题是 JS 代码没有等到 API 调用完成,因此应该在数据中的数组是“未定义的”。 How can I achieve that function "changeCurrentNode" waits until the data is here?我怎样才能实现 function "changeCurrentNode" 等到数据在这里?

Here is my function:这是我的 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:第 7 行的 console.log(nodeData) 显示以下数组:

在此处输入图像描述

And this is what I want to receive from the inner function "changeCurrentNode":这就是我想从内部 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您正在迭代一个 object,它不应该被迭代(不可迭代),而是您可以这样做: Object.keys(currentNode[0])这将返回一个包含所有键的数组

changeCurrentNode is a function which is being defined and not being called. changeCurrentNode 是一个 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 }}} changeCurrentNode();// added this }

or else you can remove the function changeCurrentNode and directly add the logic inside changeCurrentNode into the fetchAnswerFromDialogflow否则您可以删除 function changeCurrentNode 并直接将 changeCurrentNode 内部的逻辑添加到 fetchAnswerFromDialogflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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