gpt4 book ai didi

javascript - 从 promise 中返回 promise

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:32:50 26 4
gpt4 key购买 nike

我想知道如何从 promise 中返回 promise 。例如

我有这样的构造:

doAsyncStuff()  // a promise
.then( function(res) {
doAnotherAsyncStuff(res) // another promise
.then( makeSomeThings )
.then( function(anotherRes, opts) {
...
})
})
.then( ... )

我想这样写:

doAsyncStuff()  // a promise
.then( function(res) {
doAnotherAsyncStuff(res) // another promise
.then( makeSomeThings )
// and somehow push-out promise
})
.then( function(anotherRes) {
...
})
.then( ... )

我怎样才能达到这样的结果?

问题所在

var Promise = require('bluebird');
//noinspection JSUnresolvedFunction
var bcrypt = Promise.promisifyAll(require('bcrypt'));
var Sequelize = require('sequelize');
var config = require('config');

var sequelize = new Sequelize(config.get('db.connstring'));


//noinspection JSUnresolvedFunction
var User = sequelize.define('user', {
name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING,
validate: {
isEmail: true
}
},
passwordHash: {
type: Sequelize.STRING
},
isConfirmed: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
}
}, {
freezeTableName: true,
classMethods: {
login: Promise.method(function (email, password) {
if (!email || !password) throw new Error('Email and password are both required');
var rv = this
.find({where: {email: email.toLowerCase().trim()}})
.then(function (user) {

return bcrypt.compareAsync(password, user.passwordHash).then(function (res) {
console.log(email, password, res);
});
// if i dont use pacthed compare here, i have no problem ..
// return bcrypt.compare(password, user.passwordHash, function(err, res) {
// console.log(email, password, res);
// });
});
console.log('B', rv);
return rv;
})
}
});

sequelize.sync({force: true}).then(function () {
var pwd = 'pwd';
//noinspection JSUnresolvedFunction
bcrypt.hashAsync(pwd, 4).then(function (salt) {
var u1 = User.create({
name: 'u1',
email: 'u1@ex.com',
passwordHash: salt
}).then(function (result) {
User.login('u1@ex.com', pwd).then(function (res) {
console.log('A', res)
})
});
});
});

最佳答案

只是返回你的另一个 promise

doAsyncStuff()  // a promise
.then( function(res) {
return doAnotherAsyncStuff(res) // another promise
})
.then( function(anotherRes) {
...
})
.then( ... )

关于javascript - 从 promise 中返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30020999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com