一個真實的Async/Await示例

譯者按: 經過真實的代碼示例感覺Async/Await的力量。javascript

爲了保證可讀性,本文采用意譯而非直譯。另外,本文版權歸原做者全部,翻譯僅用於學習。java

既然Node.js 8已經LTS了,我想你們是時候試一試Async/Await特性了,真的很好用!它能夠幫助咱們用同步的方式寫異步代碼,極大地提升了代碼的可讀性。在過去的2年時間裏,Promise給咱們帶來了很多便利,同時也讓咱們有一些失望。node

這邊博客,我將介紹一個真實的代碼示例,它是一個REST API的controller。經過展現咱們如何從Promise切換到async/await,你講可以體會到Async/Await的神奇之處!程序員

Promise示例

下面是個人工做項目中真實的Controller代碼:json

const BPromise = require('bluebird');

const { WrongCredentialsError, DBConnectionError, EmailError } = require('./../errors');

/**
* Emulate an Express.js route call as an example
*/
loginController({}, { json: response => console.log(response) }, null)

function loginController (req, res, err) {
const { email, password } = req;

let user;

BPromise.try(() => validateUserInput(req))
.then(() => fetchUserByEmail(email))
.then(fetchedUser => user = fetchedUser)
.then(() => comparePasswords(req.password, user.password))
.then(() => markLoggedInTimestamp(user.userId))
.then(() => sendEmail(user.userId))
.then(() => generateJWT(user))
.then(token => res.json({ success: true, token }))
.catch(WrongCredentialsError, () => res.json({ success: false, error: 'Invalid email and/or password' }))
.catch(EmailError, DBConnectionError, () => res.json({ success: false, error: 'Unexpected error, please try again' }))
.catch(() => res.json({ success: false }))
}

/**
* Validate input from Request
*
* @param {Object} input
* @throws {WrongCredentialsError}
* @returns {Void}
*/
function validateUserInput(input) {
if (!input.email || !input.password) {
throw new WrongCredentialsError();
}
}

/**
* Fetch a User from the DB by Email
*
* @throws WrongCredentialsError
* @throws DBConnectionError
* @returns {BPromise}
*/
function fetchUserByEmail(email) {
const user = {
userId: 'DUMMY_ID',
email: 'konmpar@gmail.com',
password: 'DUMMY_PASSWORD_HASH'
}
return new BPromise(resolve => resolve(user));
}

/**
* Compare two password
*
* @param {String} inputPwd
* @param {String} storedPwd
* @throws {WrongCredentialsError}
* @returns {Void}
*/
function comparePasswords(inputPwd, storedPwd) {
if (hashPassword(inputPwd) !== storedPwd) {
throw new WrongCredentialsError();
}
}

/**
* Hash password
*
* @param {String} password
* @returns {String}
*/
function hashPassword(password) {
return password;
}

/**
* Mark a user's logged in timestamp
*
* @param {String} userId
* @throws DBConnectionError
* @returns {BPromise}
*/
function markLoggedInTimestamp(userId) {
return new BPromise(resolve => resolve());
}

/**
* Send a follow up email
*
* @param {String} userId
* @throws EmailError
* @returns {BPromise}
*/
function sendEmail(userId) {
return new BPromise(resolve => resolve());
}

/**
* Generate a JWT token to send to the client
*
* @param {Object} user
* @returns {BPromise<String>}
*/
function generateJWT(user) {
const token = 'DUMMY_JWT_TOKEN';

return new BPromise(resolve => resolve(token));
}

一些值得注意的要點:promise

多餘的外層變量

let user;

/* ... */
.then(fetchedUser => user = fetchedUser)
/* ... */
.then(() => sendEmail(user.userId))
/* ... */

可知,user是一個全局變量,由於我須要在Promise鏈中使用它。若是不但願定義多餘的外層變量,則須要在Promise鏈中的每個函數中都返回user變量,這樣作顯然更加糟糕。異步

煩人的Promise鏈

/* ... */
BPromise.try(() => validateUserInput(req))
/* ... */

一個Promise鏈必須從Promise開始,可是validateUserInput函數並無返回Promise,這時須要使用Bluebird。我也知道這樣寫比較奇怪…async

討厭的Bluebird

我在不少地方都使用了Bluebird,若是不用它的話,代碼會更加臃腫。所謂DRY,即Don’t repeat yourself,咱們可使用Bluebird去儘可能簡化代碼。可是,Bluebird是一個第三方依賴,若是出問題了怎麼辦?去掉Bluebird應該更好!函數

JavaScript太靈(gui)活(yi)了,出了BUG你也不知道,不妨接入Fundebug線上實時監控學習

Async/Await示例

當我放棄Promise,使用Async/Await以後,代碼是這樣的:

const { WrongCredentialsError, DBConnectionError, EmailError } = require('./../errors');

/**
* Emulate an Express.js route call as an example
*/
loginController({}, { json: response => console.log(response) }, null)

/**
*
* @param {Object} req
* @param {Object} res
* @param {Object} err
* @returns {Void}
*/
async function loginController(req, res, err) {
const { email, password } = req.email;

try {
if (!email || !password) {
throw new WrongCredentialsError();
}

const user = await fetchUserByEmail(email);

if (user.password !== hashPassword(req.password)) {
throw new WrongCredentialsError();
}

await markLoggedInTimestamp(user.userId);
await sendEmail(user.userId);

const token = await generateJWT(user);

res.json({ success: true, token });

} catch (err) {
if (err instanceof WrongCredentialsError) {
res.json({ success: false, error: 'Invalid email and/or password' })
} else if (err instanceof DBConnectionError || err instanceof EmailError) {
res.json({ success: false, error: 'Unexpected error, please try again' });
} else {
res.json({ success: false })
}
}
}

/**
* Fetch a User from the DB by Email
*
* @throws WrongCredentialsError
* @throws DBConnectionError
* @returns {Promise}
*/
function fetchUserByEmail(email) {
const user = {
userId: 'DUMMY_ID',
email: 'konmpar@gmail.com',
password: 'DUMMY_PASSWORD_HASH'
}
return new Promise(resolve => resolve(user));
}

/**
* Hash password
*
* @param {String} password
* @returns {String}
*/
function hashPassword(password) {
return password;
}

/**
* Mark a user's logged in timestamp
*
* @param {String} userId
* @throws DBConnectionError
* @returns {Promise}
*/
function markLoggedInTimestamp(userId) {
return new Promise(resolve => resolve());
}

/**
* Send a follow up email
*
* @param {String} userId
* @throws EmailError
* @returns {Promise}
*/
function sendEmail(userId) {
return new Promise(resolve => resolve());
}

/**
* Generate a JWT token to send to the client
*
* @param {Object} user
* @returns {Promise<String>}
*/
function generateJWT(user) {
const token = 'DUMMY_JWT_TOKEN';

return new Promise(resolve => resolve(token));
}

哈哈!!!

沒有外層變量

如今,全部函數都在同一個做用域中調用,再也不須要.then函數。所以,咱們再也不須要定義多餘的全局變量,也不須要作多餘的變量賦值。

沒有多餘的函數

Promise示例中的同步函數validateInputcomparePasswords的代碼能夠與異步函數寫在一塊兒,所以能夠再也不須要定義單獨的函數,代碼更少。

可讀性更高

異步代碼採用同步方式來寫,同時減小了代碼量,可讀性大大提升。

再也不須要Bluebird

原生的Promise能夠替代Bluebird,且再也不須要Bluebird的try方法了。

結論

做爲程序員,咱們應該努力完善代碼。Async/Await能夠帶來很大好處,幫助咱們寫出可讀性更高的代碼。若是你堅持使用Promise,不妨看看如何在Promise鏈中共享變量?

若是你對Async/Await感興趣的話,能夠看看這些博客:


 

相關文章
相關標籤/搜索