0

I am using the following library to have some delay in a promise:

const prom = require('util').promisify;
const delayedProm = prom(setTimeout);

i have two nested loops inside '.then(())', and in the inner loop there is if-condition. when this if-condition is satisfied i want to delay to certain amount of time, then the loop should continue normally. the promise should be resolved and returned when the two loops finish iterations.

please let me know how to achieve that sync and async

code:

return func()
.then((execs) => {

for () {
    for () {

        if (condition) {
            dely(interval)
        }
    }
}

return resolvedPromise
})
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • 1
    `please let me know how to achieve that sync and async` when working with Promises, or any asynchronous code, you can't make it `synchronous` because that defies the laws of time and space – Jaromanda X Jul 04 '18 at 10:31
  • 1
    you've created this `delayedProm` and never use it? What's the point of that? – Jaromanda X Jul 04 '18 at 10:32

1 Answers1

0

To use delay that in a loop, await is very useful:

return (async function() {
  const execs = await func();

  for () {
    for () {
      if (condition) {
        await delay(interval)
      }
    }
  }
})()

Read on:

Using async/await with a forEach loop

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • "At first I'm not sure that promisifying setTimeout automatically will work," - it does. Only the await is missing - you also have a typo. – Benjamin Gruenbaum Jul 04 '18 at 10:31
  • @benjamin okay so it checks if the callback passes an error and rejects then? I always thought it would be `functoon callback(err, result) { if(err) reject(err); else resolve(result); }` – Jonas Wilms Jul 04 '18 at 10:40
  • It has a facility - `util.promisify.custom` which functions can implement to explain how to promisify them. `setTimeout[util.promisify.custom]` tells `util.promisify` what to do - Node.js uses this to deal with non-nodeback APIs like setTimeout or `fs.exists` – Benjamin Gruenbaum Jul 04 '18 at 12:40