Follow the rules of thumb for promise development! First of all, we need to promisify the setTimeout
calls, so that we get a function which returns us a promise for it. With the RSVP Promise
constructor, it would look like this:
function delay(time) {
return new RSVP.Promise(function(resolve) {
setTimeout(resolve, time);
});
}
Now, we can chain the log statements using then
instead of passing the callback right into setTimeout
:
console.log("step 1");
delay(3000).then(function() {
console.log("step 2");
return delay(1000).then(function() {
console.log("step 3");
});
});
…and do get back a promise for when all three steps are executed.
However, the actual feature of then
is that you can unnest the callbacks now, and get exactly the same result back. So your chain would look like this:
console.log("step 1");
delay(3000).then(function() {
console.log("step 2");
return delay(1000);
}).then(function() {
console.log("step 3");
});