javascript - 有一個異步獲取數(shù)據(jù)的函數(shù)A,其他依賴這個A得到的數(shù)據(jù)的函數(shù)是否都必須是異步的?
問題描述
現(xiàn)在是這樣,函數(shù)a是Promise異步返回數(shù)據(jù),其他很多函數(shù)需要用到這個數(shù)據(jù),我現(xiàn)在是每個依賴這個數(shù)據(jù)的函數(shù)都要a().then()這樣處理
function a() { return new Promise((resolve, reject) => { .... })}function getsub(id) { return a() .then((data) => {return ..... }) .catch((err) => {...})}function tree(id) { return a() .then((data) => {return ..... }) .catch((err) => {...})}
其中有一些遞歸循環(huán)依賴,復(fù)雜度增加后我感覺我要瘋了,有沒有其他好點的寫法啊?
問題解答
回答1:可以用點函數(shù)式編程的寫法:
function mapData(call) { return () => a() .then((data) => call(data)) .catch((err) => call(null, err))}function sub(data, err) { ... }function sub2(data, err) { ... }function sub3(data, err) { ... }const getsub = mapData(sub)const getsub2 = mapData(sub2)const getsub3 = mapData(sub3)回答2:
嘗試一下 ES7 的 async/await ?或者 引入 async.js 庫,前后端通用。
回答3:如果實時性和獨立性要求都很高,那好像是沒什么辦法...不然可以嘗試緩存a...看看其他人怎么說
