patternjavascriptMinor
Calling a promise recursively
Viewed 0 times
callingrecursivelypromise
Problem
I'm trying to call a promise recursively. If I get a
Is this the best way to call a promise recursively to do what I want?
responseData with a key error I want to call the promise again and again until I don't get it._getUser (url) {
console.log('fetching url', url)
return fetch(`$(url)/api`, {
method: 'POST',
headers: {},
body: '{"key" : "body"}'
})
.then((response) => response.json())
.then((responseData) => {
console.log('Getting responseData', responseData)
if (responseData[0].error) {
alert(responseData[0].error.description)
return _getUser(url)
} else alert('User Created')
})
.catch((error) => {
console.log(error)
})
}Is this the best way to call a promise recursively to do what I want?
Solution
Two things you can improve:
Retry in all error cases by doing the recursive call in the
And limit the number of retries
Retry in all error cases by doing the recursive call in the
catch function. And limit the number of retries
_getUser (url, triesRemaining) {
console.log('fetching url', url)
return fetch(`$(url)/api`, {
method: 'POST',
headers: {},
body: '{"key" : "body"}'
})
.then((response) => response.json())
.then((responseData) => {
console.log('Getting responseData', responseData)
if (responseData[0].error) {
alert(responseData[0].error.description)
throw new Error();
} else alert('User Created')
})
.catch((error) => {
console.log(error)
if(triesRemaining>0) {
return _getUser(url,triesRemaining-1)
} else {
throw new Error('Could not create user. Max amount of tries reached');
}
})
}Code Snippets
_getUser (url, triesRemaining) {
console.log('fetching url', url)
return fetch(`$(url)/api`, {
method: 'POST',
headers: {},
body: '{"key" : "body"}'
})
.then((response) => response.json())
.then((responseData) => {
console.log('Getting responseData', responseData)
if (responseData[0].error) {
alert(responseData[0].error.description)
throw new Error();
} else alert('User Created')
})
.catch((error) => {
console.log(error)
if(triesRemaining>0) {
return _getUser(url,triesRemaining-1)
} else {
throw new Error('Could not create user. Max amount of tries reached');
}
})
}Context
StackExchange Code Review Q#142920, answer score: 2
Revisions (0)
No revisions yet.