javascript - 谁能告诉我为什么我在 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);
解决方案
您的代码中的问题:
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;
推荐阅读
- angular - Angular same route but different layout depending on logged in state
- angular - How to create multiple components with same logic or 1 component with multiple templates?
- linux - 找不到 yocto-bsp 命令
- python - 在 KMeans 中调用 model.labels 时出错
- html - 不允许启动 AudioContext。它必须在页面上的用户手势后恢复(或创建)
- python - 在我的项目中导入 Tensorflow 时出错
- typescript - 是否可以在索引签名类型中具有字段级别的泛型?
- typescript - 更改路由时是否应该从内存中释放组件?
- javascript - 从输入数字中查找数组中的下一个数字
- python - 如何解决与 win32types 相关的 PyInstaller 错误?