Estoy llamando a dos API con dos funciones diferentes y tengo un setTimeout para ambos, ¿es posible manejar sus tiempos de espera de tal manera que terminen en 10 segundos en lugar de 15 segundos?
function delay(s){ return new Promise(resolve => setTimeout(resolve,s)); } async function getXml(){ let ans; await delay(10000) const {data} = await axios.get('https://gist.githubusercontent.com/SwayamShah97/a3619c5828ac8ed8085c4ae295a855d9/raw/e4e372552e042bd8bd9e8ab87da93eb030114f86/people.xml'); xml2js.parseString(data, (err, result) => { if(err) { throw err; } ans = result }); return ans; } async function getPeople(){ await delay(5000) const { data } = await axios.get('https://gist.githubusercontent.com/SwayamShah97/0f2cb53ddfae54eceea083d4aa8d0d65/raw/d7d89c672057cf7d33e10e558e001f33a10868b2/people.json'); return data; // this will be the array of people objects }¿Hay alguna manera de ejecutar este código solo en 10 segundos, de modo que ambas API se llamen en un período de tiempo de 10 segundos?
Obligar a una o ambas funciones axios.get() a completarse por debajo de un límite de tiempo (aparte de fallar en un tiempo de espera) no es factible, ya que no controla el transporte.
Una cosa que puede hacer es forzar que una o más funciones se completen en o después de un umbral de tiempo, con algo como esto...
function padToTime(promise, interval) { // delay returns a promise that resolves after an interval const delay = interval => new Promise(resolve => setTimeout(resolve, interval)); // caller can provide a singular or an array of promises, avoiding the extra .all let promises = Array.isArray(promise) ? promise : [promise]; return Promise.all([...promises, delay(interval)]) .then(results => results.slice(0, -1)); }EDITE una buena idea de @VLAZ para agregar una promesa adicional que obligue a un tiempo mínimo (luego corte su resultado más tarde).
La persona que llama puede decir:
async function getXml(){ // op function, no calls to "delay" } async function getPeople(){ // op function, no calls to "delay" } // run these both together, have them take *no fewer than* 10s padToTime([getXml(),getPeople()], 10000).then(results => { // we'll get here in no fewer than 10sec with the promise all results })