問題描述
基本上,我正在玩弄一個用于設置先決條件的庫(想想用戶創建).由于量角器是基于 Promise 的,并且 神奇地進行了所有包裝以保留內容為了,我想到了為此目的使用承諾.我寫了一些示例代碼,但我無法解釋觀察到的行為,所以也許有人可以幫助我理解發生了什么.
Essentially I am playing around with getting a library for preconditions set up (think user creation). As protractor is promise-based and magically does all the wrapping to keep things in order, I thought of using promises for that purpose. I wrote a little sample code but I cannot explain the observed behaviour so maybe someone can help me understand what's going on.
function timeout(ms) {
var promise = protractor.promise.defer();
setTimeout(function() {
console.log('qwer');
promise.fulfill(true);
}, ms);
return promise.promise;
}
所以現在函數返回一個承諾,我假設它可以像這樣內聯使用(因為所有代碼都應該被包裝在一個控制流中)
So now the function returns a promise, which I would assume to be usable inline just like so (as all the code supposedly gets wrapped in a control flow)
describe('test', function() {
it('bla', function() {
browser.get('/');
timeout(5000);
$('some-element').click();
});
});
但是這并沒有按預期工作(即 console.log 永遠不會發生).即使 expect
從該承諾中得到結果,它也不會改變結果.如果實際上通過執行 timeout(5000).then(done)
顯式等待完成,則超時完成,但下一個操作不會在該操作之后排隊(即打開站點,單擊元素,然后5 秒后發生超時日志).
however this does not work as expected (i.e. the console.log never happens). Even when expect
ing the result from that promise, it does not change the results. If actually explicitly waiting for done by doing timeout(5000).then(done)
, the timeout completes, but the next action is not queued to after that action (i.e. site gets opened, element clicked, then after 5 seconds the log from timeout happens).
所以我真的很困惑使用控制流來確保一切都按順序執行以及觀察到的行為如何結合在一起的說法.
So I am really confused how the claims of using a control flow to make sure everything gets executed in order and the observed behaviour fit together.
推薦答案
僅僅創建一個 protractor.promise
延遲對象是不夠的——你需要告訴控制流.這通常使用 protractor.promise.controlFlow().execute()
來完成.
It's not enough just to create a protractor.promise
deferred object - you need to tell the control flow about it. This is usually done with protractor.promise.controlFlow().execute()
.
function timeout(ms) {
protractor.promise.controlFlow().execute(function() {
var deferred = protractor.promise.defer();
setTimeout(function() {
console.log('qwer');
deferred.fulfill(true);
}, ms);
return deferred.promise;
});
}
通讀 https://code.google.com/p/selenium/source/browse/javascript/webdriver/promise.js 了解所有幕后的魔法.
Read through https://code.google.com/p/selenium/source/browse/javascript/webdriver/promise.js for all the magic behind the scenes here.
這篇關于了解量角器對 Promise 的使用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!