2016-12-19 17 views
0

1.js文件如何界定它有餘地的請求變量,它被摧毀的要求完成

var a = function(){ 
    var dfd = $q.defer(); 
    http1().then(function(response1) { 
     http2(response1).then(function(response2) { 
     dfd.resolve(response2); 
    )); 
    return dfd.promise; 
} 

2.js文件

a().then(function(response){ 
    // this response is response2 
    // but what in future I wanted to access response1 
    // one way is change the response of a() and include response2 in a object 
    // but this will require a lot of changes at all places where a() is called. 


    } 
) 

但是,如果我們有一個設施後,的全球臨時變量,那麼它將需要一個小的改變。

該變量應該是臨時的,因爲它不應該干擾下一個請求。

此變量的範圍應該只針對一個請求。

var a = function(){ 
    var dfd = $q.defer(); 
    http1().then(function(response1) { 
    GlobalTempVariable.response1 = response1; 
     http2(response1).then(function(response2) { 
     dfd.resolve(response2); 
    )); 
    return dfd.promise; 
} 

2.js

a().then(function(response){ 
    // I will be able to access response2 
    // GlobalTempVariable.response1 
    } 
) 

有沒有什麼好的辦法做到這一點?

+0

是使用全局變量,最好的解決辦法您? –

回答

0

我想知道爲什麼你在node.js上使用jQuery(雖然你可以使用Promise作爲promise和you do not need it at all for other)。

但是,任何方式,你可以使用這樣的單(我的意思是,你可以在1.js保存響應1 x和從X在2.js得到它)

1.js file 
--------- 
var x = require('./x'); 
var a = function(){ 
    var dfd = $q.defer(); 
    http1().then(function(response1) { 
     x.responce1 = response1; 
     http2(response1).then(function(response2) { 
      dfd.resolve(response2) 
     }) 
    )) 
    return dfd.promise; 
} 

2.js file 
---------  
var x = require('./x'); 
a().then(function(response2){ 
    // You can access response2 as it is 
    // You can access response1 from x.responce1 
}) 

x.js file 
--------- 
module.exports = {} 
+0

這看起來是一個很好的解決方案。 – user7131571

+0

這看起來是一個很好的解決方案。 但只是爲了信息: 有什麼辦法可以爲我正在尋找的請求提供全局臨時變量。 – user7131571

+0

window.GlobalTempVariable = {response1:response1}? –

相關問題