首页 > 解决方案 > 带有环回 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 )

标签: promiseloopbackjs

解决方案


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


推荐阅读