async函数+await+setTimeout的组合 [英] Combination of async function + await + setTimeout
问题描述
我正在尝试使用新的异步功能,我希望解决我的问题将在未来帮助其他人.这是我正在运行的代码:
I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working:
async function asyncGenerator() {
// other code
while (goOn) {
// other code
var fileList = await listFiles(nextPageToken);
var parents = await requestParents(fileList);
// other code
}
// other code
}
function listFiles(token) {
return gapi.client.drive.files.list({
'maxResults': sizeResults,
'pageToken': token,
'q': query
});
}
问题是,我的 while 循环运行速度太快,脚本每秒向 google API 发送太多请求.因此,我想构建一个延迟请求的睡眠功能.因此我也可以使用这个函数来延迟其他请求.如果有其他方法可以延迟请求,请告诉我.
The problem is, that my while loop runs too fast and the script sends too many requests per second to the google API. Therefore I would like to build a sleep function which delays the request. Thus I could also use this function to delay other requests. If there is another way to delay the request, please let me know.
无论如何,这是我的新代码,它不起作用.请求的响应返回到 setTimeout 内的匿名异步函数,但我只是不知道如何将响应返回到睡眠函数 resp.到初始 asyncGenerator 函数.
Anyway, this is my new code which does not work. The response of the request is returned to the anonymous async function within the setTimeout, but I just do not know how I can return the response to the sleep function resp. to the initial asyncGenerator function.
async function asyncGenerator() {
// other code
while (goOn) {
// other code
var fileList = await sleep(listFiles, nextPageToken);
var parents = await requestParents(fileList);
// other code
}
// other code
}
function listFiles(token) {
return gapi.client.drive.files.list({
'maxResults': sizeResults,
'pageToken': token,
'q': query
});
}
async function sleep(fn, par) {
return await setTimeout(async function() {
await fn(par);
}, 3000, fn, par);
}
我已经尝试了一些选择:将响应存储在全局变量中并从睡眠函数中返回,匿名函数中的回调等.
I have already tried some options: storing the response in a global variable and return it from the sleep function, callback within the anonymous function, etc.
推荐答案
你的 sleep
函数不起作用,因为 setTimeout
没有(还?)等待
.您需要手动承诺它:
Your sleep
function does not work because setTimeout
does not (yet?) return a promise that could be await
ed. You will need to promisify it manually:
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function sleep(fn, ...args) {
await timeout(3000);
return fn(...args);
}
顺便说一句,要减慢循环速度,您可能不想使用 sleep
函数来接收回调并像这样延迟它.我推荐:
Btw, to slow down your loop you probably don't want to use a sleep
function that takes a callback and defers it like this. I recommend:
while (goOn) {
// other code
var [parents] = await Promise.all([
listFiles(nextPageToken).then(requestParents),
timeout(5000)
]);
// other code
}
这让 parents
的计算至少需要 5 秒.
which lets the computation of parents
take at least 5 seconds.
这篇关于async函数+await+setTimeout的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!