I’m trying to make a function call "sendAndMove" that involves two function inside.
And I want two functions executed in order of setting() —> goHome(). But when I wrote code like down below, it is exectued like goHome() —> setting(). So I used async/await to achieve to goal.
Is this problem happend because of asynchronous feature and Call stack?
And I want to know why setting() function doesn’t work if page changes.
Thanks a lot
function setting() {
setFinalInfo((prev)=>{return{...prev,
finalAddress: info.address,
finalCode: info.code,
finalDetailAddress: info.detailAddress,
finalPostCode: info.postCode,
finalExtraAddress: info.extraAddress}
});
}
function goHome(){
navigate("/")
}
function sendAndMove() {
setting();
goHome();
}
So I Changed to code below.
function setting() {
setFinalInfo((prev)=>{return{...prev,
finalAddress: info.address,
finalCode: info.code,
finalDetailAddress: info.detailAddress,
finalPostCode: info.postCode,
finalExtraAddress: info.extraAddress}
});
}
function goHome(){
navigate("/")
}
async function sendAndMove() { ***** Changed this part
await setting();
await goHome();
}
>Solution :
What you actually want to do is ‘channel’ from a callback to an awaitable promise, something like this:
function setting() {
return new Promise((resolve) => {
setFinalInfo((prev) => {
resolve({
...prev,
finalAddress: info.address,
finalCode: info.code,
finalDetailAddress: info.detailAddress,
finalPostCode: info.postCode,
finalExtraAddress: info.extraAddress,
});
});
});
}
function goHome() {
navigate('/');
}
async function sendAndMove() {
await setting();
goHome();
}
Btw, you don’t need to await on goHome()
since that is not an async function.