I am calling two APIs with two different functions and having a setTimeout for both, is it possible to handle their timeouts in such a way that they finish in 10s instead of 15s.
JavaScript
x
24
24
1
function delay(s){
2
return new Promise(resolve => setTimeout(resolve,s));
3
}
4
5
async function getXml(){
6
let ans;
7
await delay(10000)
8
const {data} = await axios.get('https://gist.githubusercontent.com/SwayamShah97/a3619c5828ac8ed8085c4ae295a855d9/raw/e4e372552e042bd8bd9e8ab87da93eb030114f86/people.xml');
9
xml2js.parseString(data, (err, result) => {
10
if(err) {
11
throw err;
12
}
13
ans = result
14
15
});
16
return ans;
17
}
18
19
async function getPeople(){
20
await delay(5000)
21
const { data } = await axios.get('https://gist.githubusercontent.com/SwayamShah97/0f2cb53ddfae54eceea083d4aa8d0d65/raw/d7d89c672057cf7d33e10e558e001f33a10868b2/people.json');
22
return data; // this will be the array of people objects
23
}
24
Is there a way to run this code only in 10s, so that both the APIs get called in 10s time period
Advertisement
Answer
Forcing either one or both axios.get() functions to complete below some time limit (other than failing on a timeout), isn’t doable, since you don’t control the transport.
One thing you can do is force one or more functions to complete at or after some time threshold, with something like this…
JavaScript
1
9
1
function padToTime(promise, interval) {
2
// delay returns a promise that resolves after an interval
3
const delay = interval => new Promise(resolve => setTimeout(resolve, interval));
4
// caller can provide a singular or an array of promises, avoiding the extra .all
5
let promises = Array.isArray(promise) ? promise : [promise];
6
return Promise.all([promises, delay(interval)])
7
.then(results => results.slice(0, -1));
8
}
9
EDIT good idea from @VLAZ to append an extra promise that forces minimal time (then slice its result off later).
The caller can say:
JavaScript
1
13
13
1
async function getXml(){
2
// op function, no calls to "delay"
3
}
4
5
async function getPeople(){
6
// op function, no calls to "delay"
7
}
8
9
// run these both together, have them take *no fewer than* 10s
10
padToTime([getXml(),getPeople()], 10000).then(results => {
11
// we'll get here in no fewer than 10sec with the promise all results
12
})
13