如何将 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/