兩者似乎都在做同樣的事情,即計算f(g(h(x)))
,這時這樣打電話async.compose
(f, g, h)
或_.compose
(f, g, h)
。async.compose函數和underscore.compose函數有什麼區別?
這兩個調用之間有什麼區別嗎?
兩者似乎都在做同樣的事情,即計算f(g(h(x)))
,這時這樣打電話async.compose
(f, g, h)
或_.compose
(f, g, h)
。async.compose函數和underscore.compose函數有什麼區別?
這兩個調用之間有什麼區別嗎?
顧名思義,async.compose
構成異步功能。
它通過回調參數獲取結果,而不是返回值。
我面臨同樣的情況,我需要一個函數,我從一些lib得到使用async.compose()
調用的返回值。所以我想知道:如何從async.compose()
獲得回報值?
如果write:
var gotFromAsyncCompose = async.compose(
function(gotParam, callback) {
callback(null, 'hi ' + gotParam + '!';
},
function(name, callback) {
callback(null, name.toUpperCase());
}
);
var returnValue = gotFromAsyncCompose('moe', function(err, result){
return result;
});
console.log(returnValue);
你會得到undefined
作爲returnValue
值。
因此,即使最後執行的語句是return 'A';
,async.compose()
也總是返回undefined
作爲返回值。你仍然會得到undefined
!
當談到_.compose()
,我tried the same:
var w = _.compose(
function(name){
return 'hi '+name;
},
function(got){
return got.toUpperCase() +'!';
});
);
var returnValue = w('moe');
console.log(returnValue);
這個時候,你會得到'hi MOE!'
如預期的returnValue
值。您沒有得到undefined
,就像async.compose()
的行爲一樣。
我沒有寫過任何這些組合函數,但似乎兩者之間的差異似乎是async.compose()
將不會返回任何值,而_.compose()
將返回您在最後執行的函數內傳遞給return
的值。
但是,還有一個區別:_.compose()
不處理您在函數內進行的任何異步調用。您必須在構成您的_.compose()
的所有功能中只寫同步代碼。
四個主要的區別我可以看到如4月28日的2014:
那麼哪些是首選的,哪些情況下? –
@ChintanPathak:你需要理解'async'的含義。 – SLaks