首页 > 解决方案 > 谁能告诉我为什么我在 try 块中的 setTimeout 函数不起作用?

问题描述

我有个问题。谁能告诉我为什么我在 try 块中的 setTimeout 函数不起作用?它不会等待 10000 毫秒并且简单地运行。结果,控制台显示错误消息“无法读取“未定义”的属性数据。API 应该返回一个对象,但需要一些时间来获取答案。console.log(responseInformation) 也返回“未定义”。

const fetchAnswerFromDialogflow = 
try {
      const res = await axios.post(
        `https://dialogflow.googleapis.com/v2/projects/myteachingbot-arxmxd/agent/intents:batchUpdate`,
        node,
        config
      );

      const waitForResponseAssignment = async () => {
        let nodesSavedToChatbot = await res.response.data;
        return nodesSavedToChatbot;
      };

      const responseInformation = setTimeout(
        await waitForResponseAssignment(),
        10000
      );
      
      console.log(responseInformation);

标签: javascriptasync-awaitdialogflow-essettimeout

解决方案


您的代码中的问题:

const res = await axios.post(
  `https://dialogflow.googleapis.com/v2/projects/myteachingbot-arxmxd/agent/intents:batchUpdate`,
  node,
  config
);

const waitForResponseAssignment = async () => {
   /*
    axios response doesnt have a property called response,
    so res.response.data is error.
    Also res.data is already a response from the api(res is
    not a promise so you dont have to use await below, 
    even you dont need this `waitForResponseAssignment` function)
   */
  let nodesSavedToChatbot = await res.response.data;
  return nodesSavedToChatbot;
};

// This timeout function is not correct, setTimeout
// accepts the first param as callback(but you passed a value)
// Actually you also dont need this `setTimeout`
const responseInformation = setTimeout(
  await waitForResponseAssignment(),
  10000
);

您可以使用以下代码:


const res = await axios.post(
  `https://dialogflow.googleapis.com/v2/projects/myteachingbot-arxmxd/agent/intents:batchUpdate`,
  node,
  config
);
return res.data;


推荐阅读