I have 2 HTTP requests using the Fetch API in Javascript. My main language is Java but I was tasked with a front-end project so I'm not sure if there is a simple solution to this. My problem is that the first call (hits a random server) is hitting an external endpoint that is different than the second external endpoint (this endpoint is on Azure), but the second endpoint is dependent on the first endpoint. Basically, the first endpoint is a POST requests that creates/populates an object/IoT device on the Azure website (IoT hub). So, the second request can't really do anything (in this case PATCH), until the device is showing up on the website. I noticed it usually takes a few seconds, like 1-5 seconds before it appears.
My Fetch API looks something like this:
fetch('https://first-API-endpoint-on-random-server.com/creates-thing-on-Azure', {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
// Beginning of nested Fetch
return fetch('https://second-DIFFERENT-API-endpoint-on-azure.com/tries-to-edit-thing-on-Azure', {
method: 'PATCH',
headers: myHeaders,
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
})
So basically you click a button on my website UI and its supposed to run this onClick function and create/populate the object/IoT device on Azure by the 1st Fetch API call, then the 2nd Fetch API call is supposed to "PATCH" it or edit the JSON.
The first API call always works but the problem is the second API call seems to always fail for a 404 "device not found" error, because I think the first call is finishing too fast, and then second call tries to PATCH something that doesn't even exist on the website yet. My solution was to divide out/split the API calls on to two different click events, which solves the issue as by the time the user clicks the second button, the 2nd Fetch API call/PATCH usually always succeeds.
I really want to combine them into one Function so the user never knows about the PATCH event/http call. How can I get this second Fetch to actually work?
I can provide any details you wish, please and thank you