一个关于promise的问题

User.registerAsync(new User(body), password)

.then(user => crypto.randomBytesAsync(20))

.then(buf => {

    user.activeToken = user._id + buf.toString('hex');

    user.activeExpires = Date.now() + 24 * 3600 * 1000;

    var link = config.URL + '/#/account/login/' + user.activeToken;

    mailer({

        to: body.username,

        subject: '欢迎注册依萨卡后勤端',

        html: '请点击 <a href="' + link + '" target="_blank">此处</a>激活'

    });

    return user.save();

})

.then(user => res.json({message: `已发送邮件至${ user.username }请在24小时内按照邮件提示激活`}))

.catch(err => next(err));

我想在第二个then方法中获得上一个promise的参数,也就是user。我这里是不是不应该再返回一个promise,而应该直接在前一个then方法中继续编写代码,可我觉得这样嵌套了不是很优雅,不知道有什么解决方案?我这里用的是bluebird。不知道该不该用.all方法,因为这里的promise链还是有一定的逻辑顺序的。

慕侠2389804
浏览 445回答 1
1回答

白衣染霜花

这个是不是你想要的之前没注意到&nbsp;crypto.randomBytesAsync(20)&nbsp;是个异步调用,返回的 Promise,我查了下 bluebird 的 API,和 ES6 的 Promise 差不多,所以大概应该改成这样:User.registerAsync(new User(body), password)&nbsp; &nbsp; .then(user => Promise.all([user, crypto.randomBytesAsync(20)]))&nbsp; &nbsp; .then(result => {&nbsp; &nbsp; &nbsp; &nbsp; const user = result[0];&nbsp; &nbsp; &nbsp; &nbsp; const buf = result[1];&nbsp; &nbsp; &nbsp; &nbsp; user.activeToken = user._id + buf.toString("hex");&nbsp; &nbsp; &nbsp; &nbsp; user.activeExpires = Date.now() + 24 * 3600 * 1000;&nbsp; &nbsp; &nbsp; &nbsp; var link = config.URL + "/#/account/login/" + user.activeToken;&nbsp; &nbsp; &nbsp; &nbsp; mailer({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; to: body.username,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; subject: "欢迎注册依萨卡后勤端",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; html: "请点击 <a href=\"" + link + "\" target=\"_blank\">此处</a>激活"&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; return user.save();&nbsp; &nbsp; })&nbsp; &nbsp; .then(user => res.json({ message: `已发送邮件至${user.username}请在24小时内按照邮件提示激活` }))&nbsp; &nbsp; .catch(err => next(err));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript