我如何等待多个 promises 解决但还包括设置的最小延迟?

How do I wait for multiple promises to resolve but also include a set minumum delay?

我正在调用两个具有两个不同功能的 API,并且为两者设置了 setTimeout,是否可以处理它们的超时,使其在 10 秒而不是 15 秒内完成。

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
}

有没有办法运行此代码仅在 10 秒内完成,以便在 10 秒内调用两个 API

强制一个或两个 axios.get() 函数完成低于 某个时间限制(除了因超时失败外)是不可行的,因为你不控制传输。

您可以做的一件事是强制一个或多个函数在或之后某个时间阈值完成,像这样...

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));
}

编辑 来自@VLAZ 的好主意,附加一个强制最短时间的额外承诺(然后稍后将其结果切掉)。

来电者可以说:

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
})