Reputation: 3538
I rarely write JS, and not very good at it. I know what I am trying to do, but not clear on how to write it.
I'm not used to working with async network requests
var currentURL = window.location.href.split("/profile/")[1].split("?")[0]
fetch("https://www.website.com/cap/people/profileExportPdf/20200913.pdf?memberIds="+currentURL+"&origin=profile&trackingSearchId=db44af3b-aade-4624-b8f7-6e780bcb8912%2CZbGp")
.then(resp => {return resp.json()})
.then(data => {
console.log(data.id)
canID = data.id
return canID
})
.then(canID => {
console.log(canID)
//I need to keep re-trying this URL until it returns back as Ready
fetch("https://www.website.com/cap/people/printStateAjax?id="+canID)
.then(resp=>resp.json())
.then(data=>{
console.log(data)
if(data.msg == "Ready") {
// if this returns not ready, under the else statement, have it retry
console.log('ready')
fetch("https://www.website.com/cap/people/streamPdf/"+canID)
.then(resp => {return resp.blob()})
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'file_name';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url)
})
} else {
// What do I put here to retry the fetch to /printStateAJX?id=
}
})
})
I know I should break it out as a seperate function and just keep retrying that function until data.msg returns "Ready", but I'm unsure how to write it
Any help would be greatly appreciated!
Upvotes: 0
Views: 46
Reputation: 18762
You should "break apart" the promise where you make the check and create a function that will recursively call itself until the base case (data.msg === 'Ready'
) succeeds.
var currentURL = window.location.href.split("/profile/")[1].split("?")[0]
fetch("https://www.website.com/cap/people/profileExportPdf/20200913.pdf?memberIds="+currentURL+"&origin=profile&trackingSearchId=db44af3b-aade-4624-b8f7-6e780bcb8912%2CZbGp")
.then(resp => {return resp.json()})
.then(data => {
console.log(data.id)
canID = data.id
return canID
})
.then(recursiveFunc)
function recursiveFunc(canID) {
console.log(canID)
//I need to keep re-trying this URL until it returns back as Ready
fetch("https://www.website.com/cap/people/printStateAjax?id="+canID)
.then(resp=>resp.json())
.then(data=>{
console.log(data)
if(data.msg == "Ready") {
// if this returns not ready, under the else statement, have it retry
console.log('ready')
fetch("https://www.website.com/cap/people/streamPdf/"+canID)
.then(resp => {return resp.blob()})
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'file_name';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url)
})
} else {
// What do I put here to retry the fetch to /printStateAJX?id=
return recursiveFunc(canID)
}
})
}
Assuming the rest of the code is correct, this should work.
Upvotes: 2