node.js的世界,從callback開始,不會止於async.
所有人都在罵為什么不能完全進化,其實我感覺這就是老外的細心,為了承上。這也就是為什么async其實就是promise一樣,假如不是一樣的東西,如何承上啟下。node.js異常處理一直為人詬病,其實為什么不能優雅心里沒有*數嗎?這就是設計得辣雞....好吧,我只是一個用辣雞的辣雞。
有些東西不能改變,只能自己改變自己。google了一番,我大概找出了2種我自己喜歡的方式。
一、我只是console一下,我不處理。
async function getData(){
const a = await someFunction().catch((error)=>console.log(error));
const b = await someOtherFunction().catch((error)=>console.log(error));
if(a && b ) console.log("some result")
}
二、約定法則
const go = async () => {
const readFileResult = await sureThing(readFile('some.json'));
if (readFileResult.ok) {
const {
ok,
error,
data
} = await sureThing(parseJSON(data));
if (ok) {
// use our data
} else {
return {
ok,
error
};
}
} else {
return readFileResult;
}
};
以上2種方法,我覺得是比較適合現在的。第一種的不處理,顯得更有佛性。而第二種,在保留了同步的寫法,也可以處理異步,相得益彰。
打個廣告: nodejs 學習群 atob('ODMwNTMxODc=')
https://medium.com/tech-buddy/async-await-without-try-catch-in-javascript-fdd38abf7e90
https://dzone.com/articles/easier-error-handling-using-asyncawait