我在处理 nodejs
的异步特性时遇到了一些问题。我正在使用 nodejs-mysql
连接器来获取数据。本质上,下面的代码执行查询以获取 file_url
并将信息发送到 myApi。之后应立即运行第二个查询,以使用 api(inputId
) 返回的结果更新数据库。但是,以前的异步方式不起作用(连接在处理所有内容之前关闭)。使用 async
模块执行以下操作的最佳方法是什么?
var mysql = require("mysql");
var async = require("async");
var Q = require('q'),
myApi = require('myApi')('xxxxx');
//DB
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "test"
});
//1ST Query - Fetch Urls, then upload file to api
con.query('SELECT file_url, file_id FROM myfiles', function(err, rows) {
if (err) throw err;
for (var i = 0; i < rows.length; i++) {
// File URL for upload
var fileUrl = rows[i].file_url,
createInputPromise, createEncodingProfilePromise;
var fileId = rows[i].file_id;
// Create myApi Input
createInputPromise = myApi.input.create(fileUrl);
//WHERE THE ACTION OCCURS!
Q.all([createInputPromise, createEncodingProfilePromise]).then(
function(result) {
console.log('Successfully uploaded file: ' + result[0].url + ' inputId: ' + result[0].inputId);
//2ND Query - Save the inputId return by api for each file
con.query(
'UPDATE myfiles SET myApi_input_id = ? WHERE file_id = ?', [result[0].inputId, fileId],
function(err, result) {
if (err) throw err;
console.log('Changed ' + result.changedRows + ' rows');
}
);
},
function(error) {
console.log('Error while uploading file to api:', error);
}
);
};
});
con.end(function(err) {});
最佳答案
发布的答案是很好的选择,但我最终想通过使用 async
来完成它。我遇到了 waterfall图案:
Runs an array of functions in series, each passing their results to the next in the array. However, if any of the functions pass an error to the callback, the next function is not executed and the main callback is immediately called with the error.
我结束了以下实现:
var pool = mysql.createPool({...});
function fn(callback) {
var getConnection = function(callback) {...};
async.waterfall([
doQuery.bind(null, getConnection),
doSomethingAsyncWithResult,
doUpdate(null, getConnection)
], function(err, result) {
getConnection.end();
callback(err, result);
});
}
function doQuery(connection, callback) {
connection.query(sql, callback);
}
function doSomethingAsyncWithResult(result, callback) {
...something...
callback(null, anotherResult);
}
function doUpdate(connection, result, callback) {
connection.update(sql, [result], callback);
}
关于javascript - 管理异步并在 Node 中执行多个 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35952191/