By JShinigami


2015-10-22 20:04:42 8 Comments

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

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.

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.

4 comments

@Harry 2018-02-20 09:47:04

Since Node 7.6, you can combine the functions promisify function from the utils module with setTimeout() .

Node.js

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

Javascript

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

Usage

async function main() {
    console.time("Slept for")
    await sleep(3000)
    console.timeEnd("Slept for")
}

main()

@Shl 2018-08-24 13:16:22

In nodeJS await require('util').promisify(setTimeout)(3000) can also be achieved without require by: await setTimeout[Object.getOwnPropertySymbols(setTimeout)[0]](3000‌​)

@Harry 2018-08-24 13:19:51

Interesting @Shl. I think it is less readable than my solution though. If people disagree I can add it to the solution?

@Leon li 2018-10-23 19:12:50

Nice, love the conciseness of the new native util promisify.

@FlavorScape 2018-08-20 22:01:11

The quick one-liner, inline way

 await new Promise(resolve => setTimeout(resolve, 1000));

@Shl 2018-08-24 13:11:08

This is wrong... You're waiting for the setTimeout which is not returning a Promise

@FlavorScape 2018-08-27 21:22:37

ah good catch. updated.

@Soldeplata Saketos 2018-08-28 13:58:52

let sleep = ms => new Promise( r => setTimeout(r, ms)); // a one liner function

@Liran Brimer 2018-10-07 12:37:50

even shorter :-) await new Promise(resolve => setTimeout(resolve, 5000))

@Harry 2018-10-17 22:42:12

These all copy my answer

@Leonid Beschastny 2015-10-22 23:54:58

setTimeout is not an async function, so you can't use it with ES7 async-await. But you could implement your sleep function using ES6 Promise:

function sleep (fn, par) {
  return new Promise((resolve) => {
    // wait 3s before calling fn(par)
    setTimeout(() => resolve(fn(par)), 3000)
  })
}

Then you'll be able to use this new sleep function with ES7 async-await:

var fileList = await sleep(listFiles, nextPageToken)

Please, note that I'm only answering your question about combining ES7 async/await with setTimeout, though it may not help solve your problem with sending too many requests per second.

@Bergi 2015-10-23 00:19:00

You shouldn't do that, when fn throws the errror would not be caught.

@Leonid Beschastny 2015-10-23 00:24:18

@Bergi good point!

@Dodekeract 2017-03-04 23:29:13

@Bergi I think it bubbles up to the new Promise where you can sleep.catch it.

@Bergi 2017-03-05 11:22:28

@Dodekeract No, it's in an asynchronous setTimeout callback and the new Promise callback has been done for long. It will bubble to the global context and be thrown as an unhandled exception.

@Bergi 2015-10-23 00:21:15

Your sleep function does not work because setTimeout does not (yet?) return a promise that could be awaited. 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);
}

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
}

which lets the computation of parents take at least 5 seconds.

@Anshul Koka 2017-07-27 15:32:47

Love the Promise.all approach. So simple and elegant!

@natedog 2017-08-16 02:05:31

what does the notation of var [parents] represent? I haven't seen it before and it's a difficult thing to google

@Bergi 2017-08-16 02:06:53

@NateUsher It's array destructuring

@Bergi 2017-11-23 17:09:37

@tinkerr "timeout needs to be declared async if it needs to be awaited" - Nope. A function only needs to return a promise that can be awaited (or actually, a thenable is enough). How it achieves that is up to the implementation of the function, it does not need to be an async function.

@naisanza 2018-03-13 07:22:43

I thought async/await was replacing all uses of Promises? Is there a way to use async/await and setTimeout without Promises?

@Bergi 2018-03-13 14:05:50

@naisanza No, async/await is based on promises. The only thing it replaces are then calls.

Related Questions

Sponsored Content

20 Answered Questions

[SOLVED] How and when to use ‘async’ and ‘await’

38 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 682755 View
  • 2423 Score
  • 38 Answer
  • Tags:   javascript jquery

34 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

21 Answered Questions

[SOLVED] Set a default parameter value for a JavaScript function

29 Answered Questions

5 Answered Questions

[SOLVED] Using async/await for multiple tasks

12 Answered Questions

[SOLVED] Using async/await with a forEach loop

20 Answered Questions

[SOLVED] How can I pass a parameter to a setTimeout() callback?

19 Answered Questions

[SOLVED] setTimeout or setInterval?

4 Answered Questions

[SOLVED] Why shouldn't all functions be async by default?

Sponsored Content