感觉async无法解决的异步改写
发布于 9 年前 作者 itbasketplayer 3782 次浏览 最后一次编辑是 8 年前 来自 问答

我想要把mysqldb的3个查询用async做优化,有个难点,就是如果第一个查询存在数据,后面2个就不执行,并return结果!用auto和waterfall都没有成功!求指教! function(req, username, password, done) { //md5加密 password = md5(password); // asynchronous // User.findOne wont fire unless data is sent back process.nextTick(function() {

            var findUserByUnPwSql = "select * from user where username = '" + username + "'and password ='" + password + "'";
            mysqldb.excute(findUserByUnPwSql, function (results) {
                if(results.length>0){
                    return done(null, false, req.flash('signupMessage', '该用户已存在!'));
                }else{
                    var insertUserSql = "insert into user(username,password) values('" + username + "','" + password + "')";
                    mysqldb.excute(insertUserSql, function (results) {
                        mysqldb.excute(findUserByUnPwSql, function (results) {
                            return done(null, results[0]);
                        });
                    });
                }
            });

        });

    }));
5 回复

第一个成功就返回错误,错误里面包含你需要的data

这个有什么难的? untitled1.png

我写出来了,其实想多了,结果直接return就可以,不用考虑怎么怎么存结果集。不过要注意的是,return的时候,要保证async不要再往下执行了,即callback(err);

process.nextTick(function() { async.auto({ findUserByUnPwFunc: function (callback) { var findUserByUnPwSql = “select * from user where username = '” + username + “‘and password =’” + password + “’”; mysqldb.excute(findUserByUnPwSql, function (results) { callback(null, results); }); }, insertUserFunc: [‘findUserByUnPwFunc’, function (callback, results) { var result = results.findUserByUnPwFunc; if (result.length > 0) { callback(“exist user cannot regist!”); return done(null, false, req.flash(‘signupMessage’, ‘该用户已存在!’)); } else { var insertUserSql = “insert into user(username,password) values(’” + username + “’,’” + password + “’)”; mysqldb.excute(insertUserSql, function (results) { callback(null, true); }); } }], findUserByUnPwAfterFunc: [‘findUserByUnPwFunc’, ‘insertUserFunc’, function (callback, results) { console.log(results.insertUserFunc); var findUserByUnPwSql = “select * from user where username = '” + username + “‘and password =’” + password + “’”; mysqldb.excute(findUserByUnPwSql, function (results) { callback(null, true); return done(null, results[0]); }); }] }); });

按你逻辑用sas实现了下

var sas = require('sas');
var findUserByUnPwSql = "select * from user where username = '" + username + "'and password ='" + password + "'";

var find_task = function (cb){
  mysqldb.excute(findUserByUnPwSql, function (results) {
  if(results.length>0){
  	 done(null, false, req.flash('signupMessage', '该用户已存在!'));
	 cb('$END');
  }else{
    	done(null, results[0]);
		cb();
  }
  });
}
var insert_task = function(cb){
  mysqldb.excute(insertUserSql, function (results) {
	 cb();
  });
}
sas([find_task,insert_task,find_task]);

666,不过sas是什么,也是一个异步框架?

回到顶部