我怎麼能一個接一個地發出承諾?如何解決承諾一個接一個?
waitFor(t)
,是一個函數,它返回一個在t
時間後解析的promise。我希望能夠與做的是:
waitFor(1000) Then when finished, console.log('Finished wait of 1000 millis') then
waitFor(2000) Then when finished, console.log('Finished wait of 2000 millis') then
waitFor(3000) Then when finished, console.log('Finished wait of 3000 millis')
這裏是我的嘗試:
waitFor(1000).then(function(resolve, reject) {
console.log(resolve);
}).then(waitFor(2000).then(function(resolve, reject) {
console.log(resolve);
})).then(waitFor(3000).then(function(resolve, reject) {
console.log(resolve);
}));
可惜這console.logs語句層出不窮每1秒,這意味着承諾所有人都立即致電。
我設法與像這樣的回調修正這個問題,然而這使得一切非常難看:
waitFor(1000).then(function(resolve, reject) {
console.log(resolve+' @ '+(new Date().getSeconds()));
waitFor(2000).then(function(resolve, reject) {
console.log(resolve+' @ '+(new Date().getSeconds()));
waitFor(3000).then(function(resolve, reject) {
console.log(resolve+' @ '+(new Date().getSeconds()));
});
});
});
那麼應該怎麼辦這與使得它的工作,但沒有使用難看回調地獄的承諾?
不希望的結果:http://jsfiddle.net/nxjd563r/1/
期望的結果:http://jsfiddle.net/4xxps2cg/
這可能幫助 - http://tech.transferwise.com/making-serial-xhr-calls-in-angularjs/ – FrailWords
我甚至不使用angularjs .... –
我指出這個博客有一個想法 - 去尋找一個遞歸函數,它將貫穿你的一系列承諾。 – FrailWords