我想进行两个并行的api调用。 X正在进行时,一个呼叫X检索一些数据,一个呼叫Y显示动态状态消息

问题描述 投票:0回答:1

我正在尝试并行进行两个api调用。调用X时,Y应该进行并行处理,并且它将递归调用自身,直到api X解析为止。单击按钮立即触发两个呼叫]

function X () {
return new Promise((resolve,reject) => {
// some api call
}
}

function Y () {
// some api call
// once it resolves based on the response doing a recursive call
  setTimeout(() => Y()},3000); // calling the function after 3 seconds
}

async function buttonCLick() {
const XResponse = await X();
Y();
}

以上解决方案无法正常工作。第二个呼叫Y变为同步呼叫,而不是异步。我要去哪里错了?

javascript promise async-await
1个回答
0
投票

这就是await的工作,它会在恢复之前等待异步调用完成。您的示例中缺少许多代码来提供针对您的用例的解决方案。但通常,要在更新动态状态时进行异步处理,您将需要回调或流。

let sleep = ms => new Promise(r => setTimeout(r, ms));

let doAsyncWork = async onProgress => {
  let n = 100;
  for (let i = 0; i < n; i++) {
    await sleep(Math.random() * 100);
    onProgress(i / n);
  }
  onProgress(1);
};

let updateProgress = progress => {
  document.querySelector('div').textContent = progress < 1 ? 
    `Working, ${progress * 100}%` :
    `Complete!`;
};

doAsyncWork(updateProgress);
<div></div>
© www.soinside.com 2019 - 2024. All rights reserved.