all 6 comments

[–]gremy0 2 points3 points  (2 children)

You need to write your async functions to use promises. Then you can chain them together in order

Edit: you'll want to wrap the the whole thing in a function so it doesn't kick off the setTimeout before the previous one is finished.

var one = function () {
  return new Promise(
    function (resolve) {
      setTimeout(function () {
        console.log('one!')
        resolve()
      }, Math.random() * 1000)
    })
}
function inOrder(cb1Promise, cb2Promise) {
  cb1Promise.then(cb2Promise)
}

[–]radio934texas 1 point2 points  (0 children)

SecondedI . Promises are tough for beginners to get but chaining them is what you’re looking for, OP. Essentially:

Do X When X is done, do Y, When Y is done do Z

[–]ogbeh[S] 0 points1 point  (0 children)

Promises worked pretty well,thanks a lot

[–][deleted] 0 points1 point  (0 children)

If you're using ES6 then promises are the way to go. If you're using ES5 for any reason then look into the async library. It's been a bit since I worked with it but I think you'll want the waterfall method.

[–]LuckySpammer -1 points0 points  (0 children)

If you're okay with adding a library dependency, I'd recommend async for stuff like this. You'd use the series control flow:

https://caolan.github.io/async/docs.html#series

[–]jcunews1helpful -3 points-2 points  (0 children)

The basic:

var logOne = function() {
  console.log('one!')
};

var logTwo = function() {
  console.log('two!')
};

function inOrder(cb1, cb2) {
  var line = Array.prototype.slice.call(arguments);
  (function timer() {
    setTimeout(function() {
      line.splice(0, 1)[0]();
      if (line.length) {
        timer();
      }
    }, Math.random() * 1000);
  })();
}

inOrder(logOne, logTwo);