2016-11-24 16 views
2

sequelize.jsの基本クラスを作成しようとしています。このクラスは関連するすべてのテーブルを関連付けます。 includeFk関数はこのタスクを実現します。しかし、それは約束を持っており、再帰的でなければならない。 クラス:Ecmascript 6再帰関数と約束

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

答えて

5

あなたはそれがまた約束を返すためPromise.allからエラーを処理持っていて、返された約束にそれを訓練しない限り、あなたはそれを処理する必要があります。

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が正しい範囲内にないと思います。未定義関数のエラーが発生した場合は、クラス関数を呼び出す前に変数でthisを参照してみてください。

例:

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

それが唯一のエラーを処理します。しかし、私の問題は、約束が再帰関数では機能しないということです。 – osmanraifgunes

+0

最初の問題は、約束の中に投げ込まれたエラーを処理しなければ意味エラーログを得ることができないということです。関数のスコープに何か問題があり、再帰関数が正しく機能しないと私は信じています。 – iKoala

+0

エラーログは次のとおりです。TypeError:Function.all(ネイティブ)で未定義のSymbol(Symbol.iterator) 'を読み取れません – osmanraifgunes