2016-02-05 73 views
3

我在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。

+0

我不確定你要完成什麼,你說標題在.then函數中是正確可用的。你是否試圖將它返回給函數的調用者? –

+0

是的。那麼,我們的目標是在同一範圍內訪問'response'和't'。 – user3320795

回答

1

嘗試從.finally()中返回。

.finally(function(t){ 
     return t; 
    }); 
+0

賓果!謝謝詹姆斯。下面的工作代碼。 – user3320795

0

您水溼return t從功能getTitle,但你在這裏有2個選項。

1.To做所有你需要t回調函數裏面then,或從getTitle傳遞迴調函數作爲參數

var getTitle = function(response, callback) { 
... 
.then(function(t) { 
    callback(t); 
}); 

2.To回報的承諾,並使用then來處理響應。

return horseman; 
... 
var t = getTitle(response); 
t.then(function(t){/* handle t */}); 
+0

謝謝。如何將'response'對象放入callback()中? – user3320795

+0

您將回調函數作爲參數傳遞給getTitle函數,如果需要,您可以在其中傳遞t和響應。回調(t,迴應)。 –

1

這做到了:

var getTitle = function(response) 
{ 
    console.log("Starting getTitle. response: " + response); //this works 

    var horseman = new Horseman();   // object for headless browser 

    var xyz = 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 
     .finally(function (t) { 
      horseman.close(); 
      return t; 
     }); 

    return xyz;   
} 

在調用函數:

var abc = getTitle(response); 
abc.then(function(abc) { 
    console.log("abc: " + abc); 
    response.writeHead(200, {'Content-Type': 'text/html'}); 
    response.end(abc); 

如果我把代碼的任何更多行內finally塊它沒有工作;我不知道爲什麼。我大概可以刪除response參數;需要測試一下。