I use Promise.all to fetch 2 request. But My API have rate limit one request per second. So there was an error: the server responded with a status of 429 (Too Many Requests) Is there any way to solve this problem?
const getKeywords = fetch('https://urlmyapi.com').then((res) =>
res.json().then((json) => {
if (res.ok) {
return json
}
throw json.message
})
)
const getProducts = fetch('https://urlmyapi.com').then((res) =>
res.json().then((json) => {
if (res.ok) {
return json
}
throw json.message
})
)
const [keywords, products] = await Promise.all([getKeywords, getProducts])
return {
keywords,
products,
}
As mentioned in the comments, it sounds like you want to use setTimeout to wait for one second before executing the second request. I think this will work.
async function getKeywords() {
const res = await fetch("https://urlmyapi.com/keywords");
const json = await res.json();
if (res.ok) {
return json;
}
throw new Error(json.message);
}
async function getProducts() {
const res = await fetch("https://urlmyapi.com/products");
const json = await res.json();
if (res.ok) {
return json;
}
throw new Error(json.message);
}
async function getKeywordsAndProducts() {
// make first request
const keywords = await getKeywords();
// pause for one second
await new Promise((resolve) => setTimeout(resolve, 1000));
// make second request
const products = await getProducts();
return { keywords, products };
}
Hey you should use denounce technique in this case by delaying your api calls.
const getKeywords = fetch('https://urlmyapi.com').then((res) =>
res.json().then((json) => {
if (res.ok) {
return json
}
throw json.message
})
)
const getProducts = fetch('https://urlmyapi.com').then((res) =>
res.json().then((json) => {
if (res.ok) {
return json
}
throw json.message
})
)
const reolvePromisesWithDelay=async(promises=[],delay=3000)=>{
return Promise.all(promises.map((prom, index) => {
if(index % 2){
return new Promise(resolve => setTimeout(resolve, delay));
}else{
return prom;
}
});
}
const [keywords, products] = await reolvePromisesWithDelay([getKeywords, getProducts],4000)
return {
keywords,
products,
}
So you don't want to call Promise.all then, because it will fire all function simultaneously. My suggestion is to simply fire one api call then, pause for one second and fire second api call.
Something like this:
const keywords = await getKeywords();
await new Promise(resolve => setTimeout(resolve, 1000));
const products = await getProducts();