2015-10-16 106 views
0

假設你有下面的一段代碼解決它:

var callNo1 = $http(...).then(function (response1) { 
    var callNo2 = $http(...).then(function (response2) { 
     return [response1.data, response2.data]; 
    }); 

    return callNo2; 
}).then(function (result) { 
    console.log(result); 
}); 

由於callNo2是一個承諾的[response1.data, response2.data]陣列將被記錄到控制檯。我想實現的是取得對callNo2的承諾。所以我的問題是:有沒有辦法通過return語句獲得對內部承諾的引用,以便可以通過參數訪問它。

P.S.

以下方式將被視爲作弊:

var callNo1 = $http(...).then(function (response1) { 
    var callNo2 = $http(...).then(function (response2) { 
     return [response1.data, response2.data]; 
    }); 

    return { callNo2: callNo2 }; 
}).then(function (result) { 
    console.log(['Do whatever required with result.callNo2', result.callNo2]); 
}); 
+0

你在問是否可以將'callNo2'拉出'callNo1'範圍之外,並且仍然可以訪問'response1',即使你還沒有將它帶出範圍。所以答案是否定的。確實有很多方法可以獲得你想要的結果,但是你必須在範圍之外傳遞'response1'或者'callNo2'。 – tyler

+0

也許這是更恰當的重新措辭的問題,有沒有辦法強制$ q不解決與return語句的承諾 – Lu4

+0

當然,你可以繞過承諾,就像其他任何東西,然後鏈接到它們後,他們收到 – tyler

回答

1

使用回叫功能this.Look:

function call1(callback){ 
    return $http(...).then(function (response1) { 
     var callNo2 = $http(...).then(function (response2) { 
      callback(response1.data, response2.data); 
     }); 
    }); 
} 

function calling(){ 
    call1(function(data1, data2){ 
     console.log(data1, data2); 
    }) 
} 

在隨後CALL1的功能,運行CALL2並返回promisse。當call2完成時,回調被調用。

+0

謝謝,你給了我想法,我可以解決包含我需要的所有參數的閉包函數...謝謝...! – Lu4

+1

這是一個承諾反模式。沒有意義返回承諾,不使用它 – charlietfl

+0

你指的是誰? – Lu4