Yes, you can use promises, altough for learning purposes you might want to write a pure callback solution first.
You'll want to have a look at my rules of thumb for promise development. Let's apply them here:
Every asynchronous function must return a promise.
These would be drawColorLine
, draw
, and requestAnimationFrame
in your case.
As requestAnimationFrame
is a native, primitively asynchronous function that unfortunately still takes a callback, we'll have to promisify it:
function getAnimationFrame() {
return new Promise(function(resolve) {
requestAnimationFrame(resolve); // this promise never gets rejected
// TODO: cancellation support :-)
});
}
Everything that follows an asynchronous action goes into a .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"));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…