译者按: 通过真实的代码示例感受Async/Await的力量。

为了保证可读性,本文采用意译而非直译。另外,本文版权归原作者所有,翻译仅用于学习。

既然Node.js 8已经LTS了,我想大家是时候试一试Async/Await特性了,真的很好用!它可以帮助我们用同步的方式写异步代码,极大地提高了代码的可读性。在过去的2年时间里,Promise给我们带来了不少便利,同时也让我们有一些失望。

这边博客,我将介绍一个真实的代码示例,它是一个REST API的controller。通过展示我们如何从Promise切换到async/await,你讲能够体会到Async/Await的神奇之处!

Promise示例

下面是我的工作项目中真实的Controller代码:

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());
}

相关文章:

  • 2022-12-23
  • 2021-12-04
  • 2022-12-23
  • 2021-06-29
  • 2022-02-02
  • 2021-07-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
  • 2023-01-30
  • 2021-10-31
  • 2021-08-19
  • 2021-05-17
相关资源
相似解决方案