第一次用Promise , 你们是这么用的吗?
发布于 8 年前 作者 ystyle 3540 次浏览 来自 问答
/**
 * 用户登陆
 */
router.post('/login', function (req, res, next) {
    var username = req.body.username;
    var password = req.body.password;
    var data = {success: false};
    if (!username || !password) {
        data.msg = '用户名或密码不能为空!';
        res.end(JSON.stringify(data));
    }
    redis.hget("users", username).then(function (userid) {
        if (!userid) {
            throw new Error("用户名或密码错误!");
        }
        return userid;
    }).then(function (userid) {
        return redis.hget("user:" + userid, 'password').then(function (realpassword) {
            return {userid: userid,password: realpassword}
        });
    }).then(function (result) {
        if (result.password != password) {
            throw new Error("用户名或密码错误!");
        }
        return redis.hget("user:" + result.userid, 'auth').then(function (realauth) {
            if (!realauth) {
                var auth = md5.decode(result.password + new Date());
                realauth = auth;
                redis.hmset("user:" + userid, "auth", auth);
                redis.hset("auths", auth, userid);
            }
            return realauth;
        });
    }).then(function (auth) {
        data.success = true;
        data.token = auth;
        data.msg = '登陆成功!';
        res.end(JSON.stringify(data));
    }).catch(function (error) {
        data.msg = error.message;
        res.end(JSON.stringify(data));
    });
});
2 回复

建议使用 ES6 里的 generators 或者 ES7 里的 async functions,这 2 种方式彻底解决了异步嵌套的问题。

方式没问题,但是,你需要把每个处理函数都抽取出来,不然不具有可读性

回到顶部