受到Zeit團隊部落格文章的啟發,我們的PayPal團隊在不久之前將伺服器端資料庫遷移到了Async/Await。我想要和你們分享我的經驗。
首先我們先來了解兩個名詞:
相關學習推薦:
// here is an async function async function getNumber() { return 4 // actually returns a Promise } // the same function using promises function getNumber() { return Promise.resolve(4) }
// async function to show user data async function displayUserData() { let me = await fetch('/users/me') console.log(me) }// promise-based equivalent function displayUserData() { return fetch('/users/me').then(function(me) { console.log(me) }) })Await允許你在不需要callback的情況下寫非同步程式碼。這樣做的好處是讓你的程式碼可讀性更高。而且await可以與任何promise相容,而不僅僅是用async函數創建的promise。
// basic error handling with async functions async function getData(param) { if (isBad(param)) { throw new Error("this is a bad param") } // ... } // basic promise-based error handling example function getData(param) { if (isBad(param)) { return Promise.reject(new Error("this is a bad param")) } // ... }當你使用await呼叫Promise的時候,你可以用
try/catch將其包裹,或是你需要在回傳的Promise中加入一個catch handler。
// rely on try/catch around the awaited Promise async function doSomething() { try { let data = await getData() } catch (err) { console.error(err) } } // add a catch handlerfunction doSomething() { return getData().catch(err => { console.error(err) }) }
// catch any errors in the promise and either forward them to next(err) or ignore them const catchErrors = fn => (req, res, next) => fn(req, res, next).catch(next) const ignoreErrors = fn => (req, res, next) => fn(req, res, next).catch(() => next()) // wrap my routes in those helpers functions to get error handling app.get('/sendMoney/:amount', catchErrors(sendMoney)) // use our ignoreErrors helper to ignore any errors in the logging middleware app.get('/doSomethingElse', ignoreErrors(logSomething), doSomethingElse) // controller method can throw errors knowing router will pick it up export async function sendMoney(req, res, next) { if (!req.param.amount) { throw new Error('You need to provide an amount!') } await Money.sendPayment(amount) // no try/catch needed res.send(`You just sent ${amount}`)} // basic async logging middleware export async function logSomething(req, res, next) { // ... throw new Error('Something went wrong with your logging') // ... }之前,我們一直都在用
next(err)來處理錯誤。然而,有了
async/await,我們可以將錯誤放在程式碼中的任何位置,然後router會將這些錯誤throw到Express提供的next函數中,這樣就極大的簡化了錯誤處理流程。
以上是理解JavaScript之Async/Await的新語法的詳細內容。更多資訊請關注PHP中文網其他相關文章!