I want to await a promise before implementing another logic. For example i have a request (first) and second request (second). When i will make second request, inside it i want to await the first one and after that to add additional logic. For this i created:
async function resolveAfter2Seconds() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then( json => {
console.log('first');
})
}
async function f1() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(async json => {
await resolveAfter2Seconds();
console.log('second');
})
}
const click = () => {
f1();
}
return (
<div className="App">
<button onClick={click}>click</button>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
So, when i click on the button i want to see in the console the firstly the text first
and after that second
. This is why i implemented this:
await resolveAfter2Seconds();
console.log('second');
The issue is that the code acts in this order: second
and first
. How to make the first request to occur first?
CodePudding user response:
That's because your first function resolves instantly. What you have is
async function resolveAfter2Seconds() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json()) // happens later, when the call is completed
.then( json => {
console.log('first');
})
return; // happens now
}
Just add a return statement and things will happen in the right order
async function resolveAfter2Seconds() {
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then( // etc.
}
(BTW, if you're already using async
functions, it would be probably better to get rid of the then
s and convert them to await
syntax).