promise - 带有环回 lb3 的自动更新模型 - 异步陷阱
问题描述
我只是对此发疯,请有人帮助我。
也许有人已经正确解决了这个问题?
所以我有一个包含多个数据源的应用程序,我希望它们能够正确自动更新。然而我无法相信我必须这样做......这不应该像一个共同的事情吗?
我把这个脚本放在 server/boot/20-autoUpdateDb.js
'use strict';
var cluster = require('cluster');
module.exports = function(app, cb) {
if (cluster.isWorker) {
process.nextTick(cb);
} else {
const updateDS = async dataSources => {
await dataSources.forEach(async (ds, key, arr) => {
if (ds.autoupdate) {
console.log('Proceeding with dataSource:', ds.name);
const x = await new Promise(r => {
ds.autoupdate(err => {
if (err) throw err;
console.log(
// 'Auto Updated Models [' + Object.keys(app.models) + ']:',
'Auto Updated Models in',
ds.name,
'(',
ds.adapter.name,
')',
);
r();
});
});
}
});
};
// I just couldn't find a better way as all datasources
// exist in double ex: db,Db
var appDataSources = [
app.dataSources.db,
app.dataSources.dbData,
app.dataSources.dbPool,
];
updateDS(appDataSources).then(() => {
console.log('Autoupdate of all models done.');
process.nextTick(cb);
});
}
};
作为输出我得到
Proceeding with dataSource: db
Proceeding with dataSource: dbData
Proceeding with dataSource: dbPool
Auto Updated Models in dbPool ( sqlite3 )
Autoupdate of all models done.
Web server listening at: http://localhost:3000
Browse your REST API at http://localhost:3000/explorer
Auto Updated Models in dbData ( sqlite3 )
Auto Updated Models in db ( sqlite3 )
解决方案
Array.prototype.forEach
不等待承诺。试试这个:
const appDataSources = [
app.dataSources.db,
app.dataSources.dbData,
app.dataSources.dbPool,
]
(async () => {
for (let i = 0; i < appDataSources.length; i++) {
const ds = appDataSources[ i ]
if (ds.autoupdate) {
await new Promise((resolve, reject) => {
ds.autoupdate(err => {
if (err) return reject(err)
resolve()
})
})
}
}
})()
推荐阅读
- python - 如何使用 Python 读取在线 docx 文件和 webscrape 表格内容
- mongodb - 无法在 Debian 10 上使用 Ansible 安装 MongoDB
- sql - 替换字符串中的符号 - 优化问题
- r - 删除 data.table X 列中的一些重复项,但如果 Y 列匹配条件则保留重复项
- python - 自定义 python 模块引导 .so 文件而不是 .dylib
- android - 在工具栏下方设置工具栏标题
- android - 尝试使用 proguard 运行测试
- python - WTForms 仅在输入小于 3 的字符时才返回 None
- javascript - 进行多个异步调用而不相互依赖
- java - Base64 JP2 转 JPEG 或 PNG