我正在尝试使用新的异步特性,我希望解决我的问题能够在未来帮助到其他人。这是我正在工作的代码:

  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循环运行得太快,脚本每秒向谷歌API发送太多请求。因此,我想建立一个睡眠函数延迟请求。因此,我还可以使用这个函数来延迟其他请求。如果有其他方法可以延迟请求,请让我知道。

不管怎样,这是我的新代码,它不能工作。请求的响应被返回到setTimeout内的匿名异步函数,但我只是不知道如何将响应返回到睡眠函数resp。初始asyncGenerator函数。

  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函数中返回,匿名函数中的回调等。


当前回答

Timers承诺API

await setTimeout终于在Node.js 16中实现了,不再需要使用util.promisify():

import { setTimeout } from 'timers/promises';

(async () => {
  const result = await setTimeout(2000, 'resolved')
  // Executed after 2 seconds
  console.log(result); // "resolved"
})()

官方Node.js文档:Timers Promises API(库已经在Node中构建)

其他回答

这是我2020年在AWS labdas中使用nodejs的版本

const sleep = require('util').promisify(setTimeout)

async function f1 (some){
...
}

async function f2 (thing){
...
}

module.exports.someFunction = async event => {
    ...
    await f1(some)
    await sleep(5000)
    await f2(thing)
    ...
}

从戴夫的回答中得到灵感,做了一个util

基本上传递了一个done回调在操作完成时调用。

// Function to timeout if a request is taking too long
const setAsyncTimeout = (cb, timeout = 0) => new Promise((resolve, reject) => {
  cb(resolve);
  setTimeout(() => reject('Request is taking too long to response'), timeout);
});

我是这样使用它的:

try {
  await setAsyncTimeout(async done => {
    const requestOne = await someService.post(configs);
    const requestTwo = await someService.get(configs);
    const requestThree = await someService.post(configs);
    done();
  }, 5000); // 5 seconds max for this set of operations
}
catch (err) {
  console.error('[Timeout] Unable to complete the operation.', err);
}

下面的代码可以在Chrome和Firefox以及其他浏览器中运行。

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function sleep(fn, ...args) {
    await timeout(3000);
    return fn(...args);
}

但是在Internet Explorer中,我得到了一个语法错误的“(resolve **=>** setTimeout…”

从Node 7.6开始,您可以将utils模块中的promisify函数与setTimeout()结合使用。

node . js

const sleep = require('util').promisify(setTimeout)

Javascript

const sleep = m => new Promise(r => setTimeout(r, m))

使用

(async () => {
    console.time("Slept for")
    await sleep(3000)
    console.timeEnd("Slept for")
})()
var testAwait = function () {
    var promise = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Inside test await');
        }, 1000);
    });
    return promise;
}

var asyncFunction = async function() {
    await testAwait().then((data) => {
        console.log(data);
    })
    return 'hello asyncFunction';
}

asyncFunction().then((data) => {
    console.log(data);
});

//Inside test await
//hello asyncFunction