小编Nol*_*vis的帖子

与Jsonwebtokens的Promises vs Async

我完成了一个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)

javascript asynchronous promise json-web-token

5
推荐指数
2
解决办法
5333
查看次数