[node.js] async/await如何優雅處理異常?

node.js的世界,從callback開始,不會止於async.javascript

全部人都在罵爲何不能徹底進化,其實我感受這就是老外的細心,爲了承上。這也就是爲何async其實就是promise同樣,假如不是同樣的東西,如何承上啓下。node.js異常處理一直爲人詬病,其實爲何不能優雅內心沒有*數嗎?這就是設計得辣雞....好吧,我只是一個用辣雞的辣雞。java

有些東西不能改變,只能本身改變本身。google了一番,我大概找出了2種我本身喜歡的方式。node

1、我只是console一下,我不處理。json

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")
}

2、約定法則promise

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=')async

https://medium.com/tech-buddy/async-await-without-try-catch-in-javascript-fdd38abf7e90
https://dzone.com/articles/easier-error-handling-using-asyncawait學習

相關文章
相關標籤/搜索