Making Two Fetch Requests In One Function With A Delay In Between
so I have 2 endpoints, I'm making a 'post' request to the first one and in the response I should get some kind of id that I use in the second request endpoint url. so I want to mak
Solution 1:
There is no need for a delay per se. You can place your second request in the .then
of the first request. This will ensure that your second request will run only once the first one has resolved. Another important note here, is that if you need a value of the first response in order to make the second request, you can only do that in the .then
of the first request because otherwise the value you need to make the second request will be out of scope. Here is your code with the required modification.
req = () => {
fetch('url', {
method: 'POST',
headers: {
'Authorization': bearer,
'Content-Type': 'application/json',
},
body:
})
.then(response => response.json())
.then(json => {
fetch(`url with json.id or whatever`, {
method: 'GET',
headers: {
'Authorization': bearer,
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(json => {
})
})
}
Solution 2:
You can chain your second fetch request in your first request as:
req = () => {
fetch("url", {
method: "POST",
headers: {
Authorization: bearer,
"Content-Type": "application/json"
}
body:
})
.then(response => response.json())
.then(json => {
fetch("url with the id I get from the first request", {
method: "GET",
headers: {
Authorization: bearer,
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(json => {});
});
};
Or you can use async/await
.
req = async () => {
const first = await ( awaitfetch( "url", {
method: "POST",
headers: {
Authorization: bearer,
"Content-Type": "application/json",
},
body:
} ) ).json();
const second = await ( awaitfetch( `http://some.url${ first.id }` ),
{
method: "GET",
headers: {
Authorization: bearer,
"Content-Type": "application/json",
},
} ).json();
// use the variable second as your last result here.
};
Post a Comment for "Making Two Fetch Requests In One Function With A Delay In Between"