gpt4 book ai didi

javascript - 在这种情况下如何避免回调 hell ?

转载 作者:太空宇宙 更新时间:2023-11-04 02:08:35 27 4
gpt4 key购买 nike

如您所见,我有以下代码,函数内的每个函数都依赖于封闭函数的返回值。但问题是当我继续使用这种方法编码时,就会出现回调 hell 。如何避免这个 hell ?

User.getUserDetail(req.user.id, function(userDetail) {
if(req.user.entity_id != '-1') {
Entity.getEntityPrimary(req.user.entity_id, function(entityPrimary) {
Entity.getEntityPayment(req.user.entity_id, function(entityPayment) {
if(entityPayment.length > 0) {
Entity.subscriptionInfo(entityPayment[0]['date'], entityPayment[0]['exp_date'], function(isSubscribed) {
res.render('capitol', {
user: req.user,
title: 'MCIC',
user_detail: userDetail,
entity_primary: entityPrimary,
entity_payment: entityPayment,
subscriber: true,
is_subscribed: isSubscribed
})
})
} else {
res.render('capitol', {
user: req.user,
title: 'MCIC',
user_detail: userDetail,
entity_primary: entityPrimary,
entity_payment: entityPayment,
subscriber: false
})
}
})
})
} else {
res.render('capitol', {
user: req.user,
title: 'MCIC',
user_detail: userDetail
})
}
})

模型文件如下

const MySql = require('../comms/mysql')
const User = module.exports = {}

User.getUserByUsername = function(username, callback) {
MySql.connection.query('SELECT id, username, password, is_active, email, mobile, user_type_id, entity_id FROM `user` WHERE `username` = ?', username, function(err, rows, fields) {
callback(rows)
})
}

User.getUserById = function(id, callback) {
MySql.connection.query('SELECT id, username, password, is_active, email, mobile, user_type_id, entity_id FROM `user` WHERE `id` = ?', id, function(err, rows, fields) {
callback(err, rows)
})
}

User.getUserDetail = function(id, callback) {
MySql.connection.query('SELECT first_name, last_name, dob, address_no, address_street, address_district, address_postal_code, profile_picture, user_id FROM `user_detail` WHERE `user_id` = ?', id, function(err, rows, fields) {
callback(rows)
})
}

我在生产网站中使用此代码。如何轻松地从回调 hell 过渡到结构良好的代码?

最佳答案

使用 JavaScript promise

step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});

可以制作

Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})

在此处了解更多信息 Link to Q.js

关于javascript - 在这种情况下如何避免回调 hell ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43270360/

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