How can I chain these functions together with promises?

Solution 1:

If you want to chain those functions with promises, then they have to return promises.

If you want to chain them with async module, then they have to take callbacks as arguments.

Right now they neither return a promise (or anything else), nor do they take callbacks (or anything else) as arguments. If the function doesn't take a callback and doesn't return anything then all you can do is call it and that's it. You will not be notified of any result.

Example

Callbacks

If you have 3 functions that take callbacks:

function fun1(cb) {
  setTimeout(() => {
    cb(null, "fun1");
  }, 1000);
}
function fun2(cb) {
  setTimeout(() => {
    cb(null, "fun2");
  }, 3000);
}
function fun3(cb) {
  setTimeout(() => {
    cb(null, "fun3");
  }, 100);
}

Then you can know when they finish:

fun3((err, value) => {
  console.log('fun3 finished:', value);
});

And you can easily wait for one before you start the other:

fun1((err1, val1) => {
  fun2((err2, val2) => {
    console.log("fun1 + fun2:", val1, val2);
  });
});

Promises

If your functions return promises:

function fun1() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res("fun1");
    }, 1000);
  });
}
function fun2() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res("fun2");
    }, 3000);
  });
}
function fun3() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res("fun3");
    }, 100);
  });
}

Then you can also know when they finish:

fun3().then(value => {
  console.log('fun3 finished:', value);
});

You can also easily nest the calls:

fun1().then(val1 => {
  fun2().then(val2 => {
    console.log("fun1 + fun2:", val1, val2);
  });
});

Or:

fun1()
.then(val1 => fun2())
.then(val2 => fun3())
.then(val3 => console.log('All 3 finished in series'));

etc.

To be able to do much more with both style, see documentation for:

  • http://caolan.github.io/async/
  • http://bluebirdjs.com/docs/getting-started.html
  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise