2017-11-10 10 views
1

こんにちは、私はNodeJSを比較的新しくしており、ORMとしてObjectionJSを使用しています。 各行の一部のフィールドを変更するために、自分のusersテーブルの移行スクリプトを実行します。NodeJSとObjectionJsを使用したページングクエリ

私はこの

export default class UserMigration { 

    constructor(firstId, lastId = 9000000) { 
    this.firstId = firstId; 
    this.lastId = lastId; 
    } 

    migrate() { 
    let more = true; 
    let page = 0; 
    let batchSize = 100; 
    while(more) { 
     UserModel.query().where('id', '>=', this.firstId) 
     .where('id', '<=', this.lastId) 
     .page(page, batchSize) 
     .then((result) => { 
      let users = result.results; 
      debug('Page: ', page); 
      debug('PageSize: ', users.length) 
      users.forEach((user) => { 
      // Do something here 
      }); 
      if(result.results.length < batchSize) { 
      more = false 
      } else { 
      page++; 
      } 
     }) 
    } 
    } 

} 

のようなものを作るしかし、その後、私はwhileブロックが同期的に実行されている間、クエリは非同期に実行されていることを認識し、それが正しいのですか?

一度にすべてのユーザーを返す大きなクエリを1つ作成しなくても、どのように移行できますか?

ありがとうございます!

答えて

1

私はasync/await

export default class UserMigration { 

    constructor(firstId, lastId = 9000000) { 
    this.firstId = firstId; 
    this.lastId = lastId; 
    } 

    run() { 
    this.migrateV3().then((data) => { 
     debug('All migrated'); 
     debug('data: ', data); 
    }).catch((data) => { 
     debug('Error'); 
     debug('data: ', data); 
    }); 
    } 

    async migrateV3() { 
    let more = true; 
    let page = 0; 
    let batchSize = 100; 
    while(more) { 
     try { 
     let result = await UserModel.query().where('id', '>=', this.firstId) 
      .where('id', '<=', this.lastId) 
      .page(page, batchSize); 
     let users = result.results; 
     debug('Page: ', page); 
     debug('PageSize: ', users.length) 
     for(let user of users) { 
      debug(`User ${user.id} migration start`); 
      // Do something 
     }; 
     if(result.results.length < batchSize) { 
      more = false 
     } else { 
      page++; 
     } 
     } 
     catch (err) { 
     throw err; 
     } 
    } 
    } 
} 
を使用していることを達成しています
関連する問題