gpt4 book ai didi

Javascript Promise Chaining - 它被接受了吗?

转载 作者:行者123 更新时间:2023-11-29 14:28:25 25 4
gpt4 key购买 nike

我担心我的代码,尽管它正在运行。

正如标题所说,接受了吗?因为在我的数据库中,我需要在进行 Promise 2 之前完成 Promise 1,因为我需要访问 Promise 1 的变量和结果。

简而言之,我的数据库中发生的事情是这样的:

  1. 然后插入:user_tbl
  2. 插入:login_tbl

注意在login_tbl中,有一列是user_tbl的外键。所以必须先在user_tbl中插入完毕,否则会报错。

顺便说一下,我正在使用 postgresql、knex.js 和 bcrypt这是我的代码:

//This is the function that handles the signup
const handleSignup = (req, res, db, bcrypt) => {

const { employeeId, username, password, firstName, lastName, positionSelect } = req.body;

const hash = bcrypt.hashSync(password);

if (!employeeId || !username || !password || !firstName || !lastName || !positionSelect) {
res.json({
haveEmpty: true
})
}
else{
db.transaction((trx) => {
db.select('*').from('user').where('employee_id', '=', employeeId)
.then(data => {
if(!data[0]){
db('user')
.returning('*')
.insert({
employee_id: employeeId,
username: username,
first_name: firstName,
last_name: lastName,
status: "Active",
position_id: positionSelect
})
.then(user =>{
db('login')
.returning('*')
.insert({
employee_id: employeeId,
username: username,
hash: hash
})
.then(login => {
if(login[0]){
res.json({
isSuccess: true
})
}else{
res.json({
isSuccess: false
})
}
})
.then(trx.commit)
.catch(trx.rollback);
})
.then(trx.commit)
.catch(trx.rollback);
}
else {
res.json('User already Exist!')
}
})
.then(trx.commit)
.catch(trx.rollback);
})
.catch(err => console.error(err));
}
}

最佳答案

问题可能出在 .then(data => { 部分。你在那里创建了一个新的 Promise,但你没有将它返回到另一个链接。我可能会发生,那个这个 promise 不会被解决,因为包装器 promise 不会尝试这样做,因为它不会被返回。

您可以按如下方式更改代码:

.then(data => {
if(!data[0]){
return db('user')

.then(user =>{
return db('login')

如果创建了一个 promise 但没有返回,下一个 then 什么也得不到:

Promise.resolve('abc')
.then(res => { Promise.resolve(res.toUpperCase()); })
.then(res => console.log(res) /*prints undefined*/);

block { Promise.resolve(res.toUpperCase()); } 创建了一个 Promise,但是没有返回任何东西,这意味着这个 Promise 不是进一步的链,无法解析。

一切正常,当返回 promise 时,promise 进入链中:

Promise.resolve('abc')
.then(res => { return Promise.resolve(res.toUpperCase()); })
.then(res => console.log(res) /*prints ABC*/);

.then(res => { return Promise.resolve(res.toUpperCase()); }) 可以缩短为 .then(res => Promise.resolve(res .toUpperCase())) 在这种情况下。

编辑:一些更多的 promise 链解释。

关于Javascript Promise Chaining - 它被接受了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55157977/

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