You need your functions to tell when they are finished. Promises are a good way to solve this problem.
I will stick with your source code as much as I can:
function show(msg) { return new Promise(function(resolve){ var _msg = msg; setTimeout(function() { console.log(_msg); resolve(_msg);}, 2000); }); } function show2(msg) { return new Promise(function(resolve){ console.log(msg); resolve(msg); }); } var stack = [];
Of course, it looks ugly and can be improved. As mentioned in another answer, there are task runners and flow control libraries like task.js , gen-run and co .
With co last part will be:
co(generator1);
source share