我想要做的東西像下面這樣:我可以在JavaScript Q庫中做出同步承諾嗎?
delay(2500)
.then(function() { console.log("Step 1 done") })
.then(delay(7500))
.then(function() { console.log("Step 2 done") });
所以拖延執行已經證明很多次:
function delay(ms) {
var deferred = Q.defer();
setTimeout(deferred.resolve, ms);
return deferred.promise;
}
但是,如果我運行上面的node.js我得到:
... delay of 2500ms
Step 1 done
Step 2 done
... delay of ~7500ms
而不是我希望看到:
... delay of 2500ms
Step 1 done
... delay of 7500ms
Step 2 done
在https://github.com/kriskowal/q/wiki/Examples-Gallery提供的示例中,找不到任何與promise函數鏈接的同步函數(返回一個沒有涉及任何回調的函數的函數)的示例。
任何想法如何混合異步承諾的同步行動?
我已經試過:
function synchronousPromise() {
var deferred = Q.defer();
console.log("Synchronous function call");
deferred.resolve();
return deferred.promise;
}
delay(2500)
.then(function(){synchronousPromise()})
.then(function(){delay(7500)})
.then(function(){synchronousPromise()});
而這種輸出:
... delay of 2500ms
Time now is 2013-06-20
Time now is 2013-06-20
... delay of 7500ms
..還沒有什麼,我想要的目的。
在你的第一個例子中,你試過'.then(function(){return delay(7500);})''而不是'.then(delay(7500))'? –
@FelixKling適用於第一個和第二個示例!作出你的回答,我會接受。 –
你現在可以實現這一點,而不必指定延遲時間檢查我的[答案](http://stackoverflow.com/questions/17213297/can-i-make-a-synchronous-promise-in-the-javascript-q -library/33298652#答案-33298652)。 –