如何在异步等待调用节点上设置setTimeout [英] How to setTimeout on async await call node

查看:62
本文介绍了如何在异步等待调用节点上设置setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将setTimeout添加到异步等待功能调用中?

How can I add a setTimeout to my async await function call?

我有

    request = await getProduct(productids[i]);

其中

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

我尝试过

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

并收到错误消息 TypeError:"callback"参数必须是有意义的函数.该请求位于循环中,这使我达到了api调用的速率限制.

and got the error TypeError: "callback" argument must be a function which makes sense. The request is inside of a loop which is making me hit the rate limit on an api call.

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:

You can use a simple little function that returns a promise that resolves after a delay:

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

然后,在循环中等待:

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

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

Note: I also switched your for loop to use for/of which is not required, but is a bit cleaner than what you had.

这篇关于如何在异步等待调用节点上设置setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆