1

How to use NodeJS Async (https://caolan.github.io/async/) as normal for-cycle?

for(var i = 0; i < 100; i++){
  doSomething();
}

I need serial flow but normal for-cycle not waiting until action is finished.

I am open to ES6 solutions, if any.

3 Answers 3

2

You can try to use Async/Await from ES6 which is cleaner and common shared in many standards. And in addition you don't need any dependencies from third party

const forLoopiNSeria = async () => {
  for(var i = 0; i < 10; i++){
    console.log(await doSomething(i))
  }
}


function doSomething(index) {
  return new Promise( (resolve, reject) => {
    setInterval(() => resolve(index), 500)
  }) 
}

forLoopiNSeria()
Sign up to request clarification or add additional context in comments.

2 Comments

Working as well. This is maybe better answer, because code is cleaner. Thanks
Glad I can help you
1

I believe you could always do something like this:

function asyncWhile(condition, action, ctx) {
  const whilst = function(data) {
    return condition.call(ctx, data) ?
      Promise.resolve(action.call(ctx, data)).then(whilst) :
      data;
  }
  return whilst();
}

let i = 1
asyncWhile(
() => {
  if (i <= 100) {
    i += 1
    return true
  }
  return false
},
() => {
  console.log(`iteration ${i}`)
},
)

2 Comments

I don't understand can you please add example of usage?
TypeError: condition.call is not a function
0

I found another way with usage of until function from async:

var i = 0;
var max = 100;
async.until(() => {
    i++;
    return i === max-1;
}, function (callback) {
    //doMagic()
    callback();
}, function () {
    console.log("Finished");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.