我是使用 node js 的新手,所以很可能我误解了“ promise ”和“回调 hell ”的概念。无论如何,我需要有关如何避免以下代码的建议:
var Sequelize = require('sequelize');
var DB = new Sequelize('project1db', 'john', 'password123', {
host: 'localhost',
dialect: 'mysql'
});
var DB_PREFIX = 't_';
DB.query(
'CREATE TABLE IF NOT EXISTS `'+DB_PREFIX+'user` ( ' +
'`user_id` int(11) UNSIGNED NOT NULL' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8;',{type: DB.QueryTypes.RAW})
.then(function(results) {
DB.query(
'CREATE TABLE IF NOT EXISTS `'+DB_PREFIX+'organization` ( ' +
'`organization_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT ' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8; ', {type:DB.QueryTypes.RAW})
.then(function(results) {
DB.query(
'CREATE TABLE IF NOT EXISTS `'+DB_PREFIX+'user_organization` ( ' +
'`user_id` int(11) UNSIGNED NOT NULL ' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8; ')
.then(function(){
DB.query(
'CREATE TABLE IF NOT EXISTS `'+DB_PREFIX+'content` ( ' +
'`content_id` int(11) UNSIGNED NOT NULL ' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8; ', {type:DB.QueryTypes.RAW})
.then(function(){
// more queries
}).catch(function(err){console.log(err);});
}).catch(function(err){console.log(err);});
}).catch(function(err){console.log(err);});
}).catch(function(err){console.log(err);});
忽略我使用 SQL 创建表而不是使用 Sequelize 迁移脚本这一事实,因为我只是想说明我有很多应该串联运行的 mysql 查询这一点。如果查询失败,那么我需要停止整个脚本并且不让后续的
.then()
函数触发。在我的 Sequelize 代码中,我通过嵌套大量原始查询函数调用、then 和 catch 语句来实现这一点。如果我有 100 个这样的嵌套回调语句,这将很难解决。除了嵌套所有这些回调函数之外,我还有其他选择吗?
最佳答案
Sequelize 使用(修改版) bluebird
promises 库,这意味着这应该可以工作:
var Promise = Sequelize.Promise;
Promise.each([
'CREATE TABLE IF NOT EXISTS `'+DB_PREFIX+'user` ( ' +
'`user_id` int(11) UNSIGNED NOT NULL' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8;',
'CREATE TABLE IF NOT EXISTS `'+DB_PREFIX+'organization` ( ' +
'`organization_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT ' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8; ',
'CREATE TABLE IF NOT EXISTS `'+DB_PREFIX+'user_organization` ( ' +
'`user_id` int(11) UNSIGNED NOT NULL ' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8; ',
'CREATE TABLE IF NOT EXISTS `'+DB_PREFIX+'content` ( ' +
'`content_id` int(11) UNSIGNED NOT NULL ' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8; ',
], function runQuery(query) {
return DB.query(query, { type: DB.QueryTypes.RAW });
}).then(function() {
console.log('all done');
}).catch(function(err) {
console.log(err);
});
它使用
.each()
的静态版本,它将顺序迭代数组项,将每个项传递给 runQuery
迭代器(返回一个 promise ),并在 promise 被拒绝时停止。
关于node.js - 在没有回调 hell 的情况下停止 Sequelize promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32171103/