node.js:v9.5.0
MySQL:5.7.21
MacOS:10.12
node.jsのasyncモジュールを使うことが条件となります。
MySQLの結果を加工して他の関数でいじりたいのですが、asyncモジュールのwaterfallを使って出した結果はwaterfallの外に出すことができません。
例えば下のコードの結果は、
javascript
1'use strict'; 2 3const async = require('async'); 4const mysql = require('mysql'); 5 6let arr = []; 7 8async.waterfall([ 9 (next) => { // MySQL接続 10 const conn = mysql.createConnection({ 11 host: 'localhost', 12 user: 'root', 13 password: '', 14 database: 'table' 15 }); 16 17 conn.connect((err) => { 18 if (err) throw err; 19 return next(null, conn); 20 }); 21 }, 22 (conn, next) => { 23 const sql = 'SELECT * FROM foo'; 24 conn.query(sql, (err, data) => { 25 conn.end(); 26 if (err) throw err; 27 28 // SQLの結果をpushで配列にする 29 async.eachSeries(data, (hoge, callback) => { 30 arr.push(hoge.id); 31 return callback(); 32 }); 33 return next(null, arr); 34 }); 35 } 36], (err, arr) => { 37 if (err) throw err; 38 console.log('asyncの中:', arr); // [ 80, 81, 86, 87, 88, 89, 91, 17, 31, 32, 33 ] 39}); 40 41console.log('asyncの外:', arr) // []
text
1asyncの外: [] 2asyncの中: [ 80, 81, 86, 87, 88, 89, 91, 17, 31, 32, 33 ]
のようなイメージとなります(当たり前ですが)。
結果arrをwaterfallの外に出す方法はないでしょうか。
回答4件
あなたの回答
tips
プレビュー