Yes, you can use promises, but for training purposes you can first write a clean inverse solution.
You want to look at my rules of thumb for developing promises. Apply them here:
Each asynchronous function should return a promise.
In your case it will be drawColorLine , draw and requestAnimationFrame .
Since requestAnimationFrame is a native, primitive asynchronous function, which unfortunately still requires a callback, we have to promisify :
function getAnimationFrame() { return new Promise(function(resolve) { requestAnimationFrame(resolve);
Everything that follows the asynchronous action goes into the .then() callback:
function drawColorLine(start, end, color) { β¦ // initialisation function draw() { β¦ // do work // always return a promise: if (/* furter work */) { i++; return getAnimationFrame().then(draw); // magic happens here :-) } else { return Promise.resolve(β¦); // maybe have a path object as eventual result? // or anything else, including nothing (no arg) } } return draw(); // returns a promise - but don't forget the `return` }
Voila!
drawColorLine([40, 40], [100, 40], '#116699').then(function() { return drawColorLine([40, 40], [40, 100], '#bb11dd'); }).then(console.log.bind(console, "both lines drawn"));
Bergi Apr 27 '15 at 21:51 2015-04-27 21:51
source share