在Node上执行异步多个Mysql查询

时间:2016-12-01 15:33:52

标签: mysql node.js underscore.js q deferred

我在Mysql中使用节点,这就是我的问题。

我尝试在我的数据库中添加新照片并将其作为数组返回

这是我的功能:

function addNewPhotos(_id, files) {
var deferred = Q.defer();
var new_photos = []
_.each(files, function (one) {
    var data = [
        one.path,
        _id,
        0
    ]
    var sql = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)';
    db.connection.query(sql, data, function (err, result) {

        if (err)
            deferred.reject(err.name + ': ' + err.message);
        var sql = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
        if (result){
            db.connection.query(sql, [result.insertId], function(err, photo) {
                if (err) deferred.reject(err.name + ': ' + err.message);
                if (photo) {
                    new_photos.push(photo[0]);
                }
            });
        }
    })
})
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise}

插入效果很好但我无法检索结果以将其发送回客户端。 (我的数组是空的)

感谢。

2 个答案:

答案 0 :(得分:2)

始终在最低级别进行宣传,在这种情况下db.connection.query()

if(!db.connection.queryAsync) {
    db.connection.queryAsync = function(sql, data) {
        return Q.Promise(function(resolve, reject) { // or possibly Q.promise (with lower case p), depending on version
            db.connection.query(sql, data, function(err, result) {
                if(err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    };
}

现在更高级别的代码变得非常简单:

function addNewPhotos(_id, files) {
    var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
        sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
    return Q.all(files.map(function(one) {
        return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
            return db.connection.queryAsync(sql_2, [result.insertId]);
        });
    }));
};

为防止单一故障导致整个过程失败,您可能会选择捕获单个错误并注入某种默认值;

function addNewPhotos(_id, files) {
    var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
        sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?',
        defaultPhoto = /* whatever you want as a default string/object in case of error */;
    return Q.all(files.map(function(one) {
        return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
            return db.connection.queryAsync(sql_2, [result.insertId]);
        }).catch(function() {
            return defaultPhoto;
        });
    }));
};

答案 1 :(得分:-1)

完成所有操作后,在异步循环函数中返回

MatchResult