Reputation: 517
I am training in the use of the fetch().
As you can see in the code below, I decided to put a fetch into a promise of the first fetch, but even if that code works fine I am not sure if this is a good or a bad practice.
And if the code written is a bad practice, could someone address me to a good one?
Thank you in advance.
function callOne () {
let q = 'q='+input.value;
fetch(urlOne)
.then(res => res.json())
.then(data => {
console.log(data);
callTwo(q);
})
.catch(err => {
console.log(err);
});
}
function callTwo(q) {
fetch(urlTwo)
.then(res => res.json())
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
}
Upvotes: 0
Views: 227
Reputation: 3878
it depends, you could run them in parallel when they are independent like in your code. something like:
Promise.all([callOne(), callTwo()]).then(([dataOne, dataTwo]) => {/**/})
this way they wont be nested, and you can maintain them better. and will be done faster. But if you have to wait for the data from first one to pass to the second one, then you have to that like you did. although, i think i would write them like:
callOne()
.then(/*do something with first response and pass to second call*/)
.then(callTwo)
.then(/*do something with second data*/)
in both cases it would be better if in your call functions, you return the fetch. return fetch(...).then(...).catch(...)
this way you could chain those like you would chain promises normally. callOne().then(...)
Upvotes: 1