2016-09-29 137 views
2

我所試圖做的是基本上如何從一個本身使用promise的函數返回promise?

function test() { 
getSomeValue().then(function (data) { 
    //process data 
}); 
} 

function getSomeValue() { 
//do some long process 
return new Promise(function (resolve, reject) { 
    resolve(result); 
}); 
} 

function getSomeOtherValue() { 
//do some long process 
return new Promise(function (resolve, reject) { 
    resolve(result); 
}); 
} 

功能測試調用返回一個承諾,然後對返回的數據一些計算功能。這部分工作正常。現在功能getSomeValue需要調用另一個函數,它也返回一個承諾。我如何退還getSomeValue的承諾,其中也等待getSomeOtherValue完成。

讓我知道是否需要其他信息。

+0

你可以做鏈接,'。然後()。然後,()......' – Rayon

回答

1

你可以只連鎖getSomeOtherValuegetSomeValue

function getSomeValue() { 
    //do some long process 
    return new Promise(function (resolve, reject) { 
     resolve(result); 
    }).then(getSomeOtherValue); 
} 

如果你想切換順序則:

function getSomeValue() { 
    //do some long process 
    return getSomeOtherValue().then(function() { 
     return new Promise(function (resolve, reject) { 
      resolve(result); 
     });   
    } 
} 

然而,這僅僅是爲了說明。你可以設計你的諾言,讓您可以在更高層次上有效地把它們連:

function test() { 
    getSomeOtherValue() 
     .then(getSomeValue) 
     .then(function (data) { 
      //process data 
     }); 
} 
+0

實際上getSomeOtherValue()需要之前調用。我需要來自getSomeOtherValue()的數據,然後根據那個 –

1

等待getSomeOtherValue功能得到解決,你需要解決getSomeValue功能的承諾,從getSomeOtherValue返回的承諾功能。下面的代碼應該有希望有意義

function test() { 
getSomeValue().then(function (data) { 
    //process data 
}); 
} 

function getSomeValue() { 
//do some long process 
return new Promise(function (resolve, reject) { 
    getSomeOtherValue().then(function (data) { 
     resolve(result); 
    });   
}); 
} 

function getSomeOtherValue() { 
//do some long process 
return new Promise(function (resolve, reject) { 
    resolve(result); 
}); 
} 
2

擺脫getSomeOtherValue值getSomeValue前,只需撥打getSomeOtherValue功能,然後再鏈與另一個函數來處理getSomeValue值,那麼最後的結果返回給調用者(測試功能)

​​
+0

添加說明生成響應 – alpha