小编Kyl*_*e R的帖子

避免在 then 函数 JS 中嵌套承诺

我有一个异步函数“doApiRequest”,它在“then”函数内部调用...

doSomething()
  .then(() => {
    return doApiRequest();
  })
  .then((apiResult) => {
    doSomethingElse(apiResult);
  });
Run Code Online (Sandbox Code Playgroud)

问题是 doApiRequest 返回一个带有该 API 请求最终结果的 Promise。但是,根据我正在使用的 API 的性质,涉及请求速率限制。我计划通过让每个 API 请求将自身添加到队列来处理这个问题,然后当队列在等待速率限制后释放请求时,API 请求将完成解析。虽然我可以做类似...

doSomething()
  .then(() => {
    return waitForRateRefresh();
  })
  .then(() => {
    return doApiRequest();
  })
  .then((apiResult) => {
    doSomethingElse(apiResult);
  });
Run Code Online (Sandbox Code Playgroud)

我最终可能会收到许多“doApiRequest”调用,因此必须在每个调用上链接“waitForRateRefresh”似乎是一个糟糕的方法,而且我还必须使其工作,以便它可以传递来自先前 then 语句的数据。我想做的是在“doApiRequest”本身内部处理这个问题。

'doApiRequest' 看起来像这样

doApiRequest(){
  return new Promise((resolve, reject) => {
    waitForRateRefresh().then(() => {
      //http call
      resolve(someValue);
    };
  });
}
Run Code Online (Sandbox Code Playgroud)

但是,我正在尝试找到一种不涉及嵌套 Promise 的方法。还有什么其他方法可以解决这个问题。我想到的另一种方法是使用 Async/Await,有没有其他方法可以只用承诺来做到这一点?从“doApiRequest”返回带有附加 then 函数的 Promise 会发生什么(或者甚至可能),例如......

return waitForRateRefresh().then(() => new Promise(..../http call));
Run Code Online (Sandbox Code Playgroud)

在调用“doApiRequest”的原始 then 函数中,它会接收“waitForRateRefresh”返回的值,还是向下遍历附加到它的 …

javascript node.js promise async-await

0
推荐指数
1
解决办法
5037
查看次数

标签 统计

async-await ×1

javascript ×1

node.js ×1

promise ×1