I have an asynchronous function 'doApiRequest' that is called inside of a 'then' function...
doSomething()
.then(() => {
return doApiRequest();
})
.then((apiResult) => {
doSomethingElse(apiResult);
});
The issue being that doApiRequest returns a Promise with the eventual result of that API request. However, do to the nature of the API I'm working with there is a request rate limit involved. I plan on handling that by having each API request add itself to a queue, and then when the queue releases the request after waiting for the rate limit, the API request will finish resolving. While I could do something like...
doSomething()
.then(() => {
return waitForRateRefresh();
})
.then(() => {
return doApiRequest();
})
.then((apiResult) => {
doSomethingElse(apiResult);
});
I may end up having many 'doApiRequest' calls, so having to chain a 'waitForRateRefresh' on each seems like a bad method and I'd also have to make it work so it can pass along the data from previous then statements. What I'd like to do is handle this inside of 'doApiRequest' itself.
'doApiRequest' would look something like this
doApiRequest(){
return new Promise((resolve, reject) => {
waitForRateRefresh().then(() => {
//http call
resolve(someValue);
};
});
}
However I'm trying to find a way to do this that doesn't involve nesting Promises. What other ways would there be to go about this. Another way I've though of doing it is by using Async/Await instead, is there any other way of doing it with just promises? What happens (or is it even possible) to return a Promise with an attached then function from 'doApiRequest' like...
return waitForRateRefresh().then(() => new Promise(..../http call));
In the original then function where 'doApiRequest' is called - will it receive the value returned by 'waitForRateRefresh', or the result of traversing down the then chain attached to it.
Thanks for any insights
'doApiRequest' would look something like thisavoid the promise constructor antipattern ... the content of that function is simplyreturn waitForRateRefresh().then(() => { //http call return someValue; };.then(() => { return waitForRateRefresh(); })and the same fordoApiRequest... there is no incoming "value" anyway