[英]How can I make sure that function 1 ends before function 2 starts within useeffect hook?
I created a chatbot and want to initiate two Dialogflow API calls within a useEffect Hook.我创建了一个聊天机器人并想在 useEffect Hook 中启动两个 Dialogflow API 调用。 Function 1 and function 2 are both async api calls.
Function 1 和 function 2 都是异步 api 调用。 The wanted result is that it first finishes function 1 and then starts with function 2, but currently function 2 returns the value faster than function 1.
想要的结果是它首先完成 function 1,然后从 function 2 开始,但目前 function 2 比 function 1 返回值更快。
Do you have any idea how I can tell function 2 to wait until function 1 returns a value?你知道我如何告诉 function 2 等到 function 1 返回一个值吗?
useEffect(
() => {
createChatSessionId();
fetchEventAnswerFromDialogflow("Startevent" + chatId, chatId); // function 1
fetchEventAnswerFromDialogflow("Frageevent1", chatId); // function 2
}, // eslint-disable-next-line
[]
);
API Calls are asynchronous. API 调用是异步的。 When the compiler hits an async statement, it doesnt wait for it to finish, instead calls next statement.
当编译器遇到异步语句时,它不会等待它完成,而是调用下一条语句。
Option one, (Using.then block):-选项一,(Using.then 块):-
useEffect(
() => {
createChatSessionId();
fetchEventAnswerFromDialogflow("Startevent" + chatId, chatId).then(rep=>{
fetchEventAnswerFromDialogflow("Frageevent1", chatId);})
.catch(err){
console.log(err)
}
}, // eslint-disable-next-line
[]
);
Option two - As per ES6 using async await.选项二 - 根据 ES6 使用异步等待。 I'd suggest not to make useEffect callback as async, instead make a new async function inside useEffect and call that.
我建议不要将 useEffect 回调设为异步,而是在 useEffect 中创建一个新的异步 function 并调用它。
useEffect(
() => {
createChatSessionId();
const getData = async() =>{
await fetchEventAnswerFromDialogflow("Startevent" + chatId, chatId);
await fetchEventAnswerFromDialogflow("Frageevent1", chatId); //Can remove await
//here, depending upon usecase
}
getData();
}, // eslint-disable-next-line
[]
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.