osm*_*nes 2 javascript node.js sequelize.js ecmascript-6
我正在尝试为sequelize.js编写基类.该类将关联所有相关表.includeFk函数实现此任务.但它有一个承诺,应该是递归的.课程:
class base {
constructor(table, depth) {
this._table = table;
this._depth = depth;
}
includeFK(table, depth, includes) {
return new Promise((resolve, reject) => {
if (depth <= this._depth) {
for (var att in table.tableAttributes) {
table.belongsTo(m, {
as: m.name,
foreignKey: att
})
includes.push({
model: m
});
}
}
Promise.all(
Object.keys(table.associations).forEach(tbl => {
this.includeFK(table.associations[tbl].target, depth + 1, includes);
}
)).then(results => {
resolve(true)
});
} else {
resolve(true);
}
});
all(query) {
return new Promise((resolve, reject) => {
var tmp = this;
var includes = [];
Promise.all([
this.includeFK(tmp._table, 1, includes),
this.includeLang()
]).then(function() {
tmp._table.findAll({
include: includes
}).then(function(dbStatus) {
resolve(dbStatus);
});
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
(node:25079)UnhandledPromiseRejectionWarning:未处理的promise拒绝(拒绝ID:3):TypeError:无法读取未定义的属性'Symbol(Symbol.iterator)'(节点:25079)弃用警告:不推荐使用未处理的拒绝承诺.将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程.(node:25079)UnhandledPromiseRejectionWarning:未处理的promise promise(拒绝id:4):TypeError:无法读取未定义的属性'Symbol(Symbol.iterator)'
您可以处理错误,Promise.all因为它还会返回一个承诺,您需要处理它,除非您将其训练为返回的承诺.
Promise.all([...])
.then(...)
.catch(function(err) {
console.error(err);
reject(err);
});
Run Code Online (Sandbox Code Playgroud)
编辑:
var promiseArr = [];
Object.keys(table.associations).forEach(tbl => {
promiseArr.push(
self.includeFK(table.associations[tbl].target, depth + 1, includes)
);
});
Promise.all(promiseArr)
.then(results => {
resolve(true)
});
Run Code Online (Sandbox Code Playgroud)
我也认为你的this绑定不在正确的范围内.如果得到未定义函数的错误,请this在调用类函数之前尝试使用变量引用.
例:
includeFK(table, depth, includes) {
var self = this; //ref this and use it later
...
...
self.includeFK();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1540 次 |
| 最近记录: |