我在JavaScript中使用鏈接承諾(我認爲)。鏈中有一個then()函數。我想訪問promise中的變量,或者通過HTTP響應對象返回變量。訪問Javascript承諾鏈中的變量
var getTitle = function(response)
{
console.log("Starting getTitle. response: " + response); //this works
var horseman = new Horseman(); // object for headless browser
horseman
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0")
.open('http://www.google.com/ncr')
.type('input[name="q"]', 'github')
.click("button:contains('Google Search')")
.keyboardEvent("keypress",16777221) // press Enter
.waitForSelector("div.g")
.title() // gets the title of the page
.then(function(t) {
console.log("title: " + t); // this works
})
.close();
console.log("title outside: " + t); // this gives 'undefined'
return t; // returns 'undefined'
}
如何提取't'變量?我也試過路過「響應」到功能類似
.then(function(t, response) {
但是當我登錄的迴應「,這是不確定的。如果我能以某種方式傳遞響應對象,那也是可行的。
如果我做
var test = horseman...
測試成爲一個承諾的對象,但它不包含變量t。
我不確定你要完成什麼,你說標題在.then函數中是正確可用的。你是否試圖將它返回給函數的調用者? –
是的。那麼,我們的目標是在同一範圍內訪問'response'和't'。 – user3320795