使用rsvp.js或任何其他的承諾/ A +實現我怎麼能把這樣的代碼......如何嵌套一個定時器,轉換爲承諾
console.log('step 1');
setTimeout(function() {
console.log('step 2');
setTimeout(function() {
console.log('step 3');
}, 100);
}, 300);
爲承諾實施?
使用rsvp.js或任何其他的承諾/ A +實現我怎麼能把這樣的代碼......如何嵌套一個定時器,轉換爲承諾
console.log('step 1');
setTimeout(function() {
console.log('step 2');
setTimeout(function() {
console.log('step 3');
}, 100);
}, 300);
爲承諾實施?
創建一個延遲函數,它返回一個Promise,它在setTimeout
中經過指定的時間後,實際上解析它,就像thi小號
function delay(time) {
return new RSVP.Promise(function (resolve) {
setTimeout(resolve, time);
});
}
,然後你可以調用它像這樣
console.log("step 1");
delay(3000)
.then(function() {
console.log("step 2");
return delay(1000);
})
.then(function() {
console.log("step 3");
});
鏈的承諾:
// Set up the functions which contain the promises
function step1() {
return new RSVP.Promise(function(resolve, reject) {
resolve();
});
}
function step2() {
return new RSVP.Promise(function(resolve, reject) {
setTimeout(function() {
resolve();
}, 300);
});
}
function step3() {
return new RSVP.Promise(function(resolve, reject) {
setTimeout(function() {
resolve();
}, 100);
});
}
// Now execute them:
step1()
.then(step2)
.then(step3)
你可以在這裏閱讀更多:如果你沒事使用qhttp://www.toptal.com/javascript/javascript-promises
,還有烤成庫一個非常簡單的解決方案:
console.log('step 1');
Q.delay(300).then(function() {
console.log('step 2');
return Q.delay(200);
}).then(function() {
console.log('step 3');
});
按照rules of thumb for promise development!首先,我們需要promisify調用setTimeout
,以便我們得到一個函數,它返回給我們一個承諾。隨着the RSVP Promise
constructor,它應該是這樣的:
function delay(time) {
return new RSVP.Promise(function(resolve) {
setTimeout(resolve, time);
});
}
現在,我們可以使用then
而不是通過回調右轉入setTimeout
chain日誌聲明:
console.log("step 1");
delay(3000).then(function() {
console.log("step 2");
return delay(1000).then(function() {
console.log("step 3");
});
});
...和你回來的承諾當所有三個步驟都執行完畢。
但是,then
的實際功能是您現在可以unnest the callbacks,並得到完全相同的結果。所以你的連鎖店看起來是這樣的:
console.log("step 1");
delay(3000).then(function() {
console.log("step 2");
return delay(1000);
}).then(function() {
console.log("step 3");
});