How to setTimeout on async await call node

試著忘記壹切 提交于 2020-12-04 18:37:02

问题


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

I have

    request = await getProduct(productids[i]);

where

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

I've tried

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

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

回答1:


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

And, then await that inside your loop:

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

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




回答2:


Actually, I have a pretty standard chunk of code that I use to do that:

function PromiseTimeout(delayms) {
    return new Promise(function (resolve, reject) {
        setTimeout(resolve, delayms);
    });
}

Usage:

await PromiseTimeout(1000);

If you're using Bluebird promises, then it's built in as Promise.timeout.

More to your problem: Have you checked API docs? Some APIs tell you how much you have to wait before next request. Or allow downloading data in larger bulk.




回答3:


As of node v15 you can use the Timers Promises API:

const timersPromises = require('timers/promises');

async function test() {
  await timersPromises.setTimeout(1000);
}

test();

Note that this feature is experimental and may change in future versions.



来源:https://stackoverflow.com/questions/50091857/how-to-settimeout-on-async-await-call-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!