node.js - 如何在异步等待调用 Node 上设置超时

标签 node.js callback async-await settimeout

如何将 setTimeout 添加到我的异步等待函数调用中?

我有

    request = await getProduct(productids[i]);

在哪里

const getProduct = async productid => {
        return requestPromise(url + productid);
   };

我试过了

    request = await setTimeout((getProduct(productids[i])), 5000);

并得到错误 TypeError: "callback"argument must be a function 这是有道理的。该请求在一个循环内,这使我达到了 api 调用的速率限制。

exports.getProducts = async (req, res) => {
  let request;
  for (let i = 0; i <= productids.length - 1; i++) {
    request = await getProduct(productids[i]);
    //I want to wait 5 seconds before making another call in this loop!
  }
};

最佳答案

您可以使用一个简单的小函数来返回在延迟后解析的 promise :

function delay(t, val) {
   return new Promise(function(resolve) {
       setTimeout(function() {
           resolve(val);
       }, t);
   });
}

// or a more condensed version
const delay = (t, val) => new Promise(resolve => setTimeout(resolve, t, val));

然后,在你的循环中await:

exports.getProducts = async (req, res) => {
  let request;
  for (let id of productids) {
    request = await getProduct(id);
    await delay(5000);
  }
};

注意:我还将您的 for 循环切换为使用 for/of,这不是必需的,但比您使用的要干净一些。


或者,在现代版本的 nodejs 中,您可以使用 timersPromises.setTimeout() 这是一个返回 promise 的内置计时器(从 nodejs v15 开始):

const setTimeoutP = require('timers/promises').setTimeout;

exports.getProducts = async (req, res) => {
  let request;
  for (let id of productids) {
    request = await getProduct(id);
    await setTimeoutP(5000);
  }
};

关于node.js - 如何在异步等待调用 Node 上设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50091857/

相关文章:

javascript - 理解 module.exports 与回调

c# - 等待 Task.Delay(foo);需要几秒而不是毫秒

c# - 返回 IAsyncEnumerable<T> 但结果不进行流式传输的 API

python - 如何让 uvicorn 运行异步构建的应用程序?

node.js - 如何修复 eslint 错误 - 无关 Node/无无关需求

xml - NodeJs CMS - 构建 CMS 时将 XML 或 JSON 作为存储格式

javascript - 如何使用 MVC Ajax.BeginForm 在 AjaxOptions OnComplete 函数中获取源元素

javascript - 类似的 $http 请求首先陷入挂起状态,然后 NodeJS 服务器失败

node.js - 如何在 VSCode 中调试使用 PM2 运行的 Node.js 应用程序?

python - 如何更新 bokeh 中的 customJS 函数中的全局 python 变量?