gpt4 book ai didi

javascript - 具有 promise 的 Ecmascript 6 递归函数

转载 作者:搜寻专家 更新时间:2023-11-01 00:21:35 24 4
gpt4 key购买 nike

我正在尝试为 sequelize.js 编写一个基类。此类将关联所有相关表。 includeFk 函数实现这个任务。但它有一个 promise ,应该是递归的。类:

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);
});
});
});
}
}

错误:

(node:25079) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined (node:25079) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. (node:25079) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined

最佳答案

您可以处理来自 Promise.all 的错误,因为它也返回一个 promise ,您需要处理它,除非您将其训练为返回的 promise 。

Promise.all([...])
.then(...)
.catch(function(err) {
console.error(err);
reject(err);
});

编辑:

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)
});

我还认为您的 this 绑定(bind)不在正确的范围内。如果您遇到未定义函数的错误,请在调用类函数之前尝试使用变量引用 this

例子:

includeFK(table, depth, includes) {
var self = this; //ref this and use it later
...
...
self.includeFK();

关于javascript - 具有 promise 的 Ecmascript 6 递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40782800/

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