我完成了一个Node app教程并回过头来用async/await重写代码,以便更好地了解它是如何完成的.但是我有一个路由处理程序,如果不使用promises,我就无法做到:
getProfile: function(id){
return new Promise(function(resolve, reject){
Profile.findById(id, function(err, profile){
if (err){
reject(err)
return
}
resolve(profile.summary())
})
})
}
Run Code Online (Sandbox Code Playgroud)
我改写为:
getProfile: async (req, res, next) => {
const profileId = req.params.id;
const profile = await Profile.findById(profileId);
res.status(200).json(profile)
}
Run Code Online (Sandbox Code Playgroud)
编辑2:好的我也意识到我改写了:
create: function(params){
return new Promise(function(resolve, reject){
var password = params.password
params['password'] = bcrypt.hashSync(password, 10)
Profile.create(params, function(err, profile){
if (err){
reject(err)
return
}
resolve(profile.summary())
})
})
}
Run Code Online (Sandbox Code Playgroud)
如
newProfile: async (params, res, next) => {
const newProfile = new Profile(params);
const …Run Code Online (Sandbox Code Playgroud)