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中的匿名异步函数,但我只是不知道如何将响应返回给sleep函数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);
}
我已经尝试了一些选项:将响应存储在全局变量中并返回它来自sleep函数,匿名函数内的回调等等。
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.
推荐答案
你的睡眠
函数不起作用,因为 setTimeout
没有(还是?)返回一个可能 await
ed的承诺。你需要手动宣传它:
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'd rather recommend to do something like
while (goOn) {
// other code
var [parents] = await Promise.all([
listFiles(nextPageToken).then(requestParents),
timeout(5000)
]);
// other code
}
可以计算父母
至少需要5秒钟。
which lets the computation of parents
take at least 5 seconds.
这篇关于async函数+ await + setTimeout的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!