鍍金池/ 問答/數(shù)據(jù)庫  HTML/ node在操作mongodb的時候怎么才算充分體現(xiàn)異步特性?

node在操作mongodb的時候怎么才算充分體現(xiàn)異步特性?

用的中間件是mongoose
要怎么樣的操作數(shù)據(jù)庫才能算是異步的?異步的話要怎么確定是否入庫成功?

比如刪除某一條

var User = require("./mongouser.js");
var wherestr = {'username' : '什么鬼'};
    
    User.remove(wherestr, function(err, res){
        if (err) {
            console.log("Error:" + err);
        }
        else {
           // console.log("Res:" + res);
           res.send("刪除成功");
            //刪除成功在這里,這樣就有了阻塞,如果數(shù)據(jù)庫因為某些原因沒有響應(yīng),那么就一直停在這里了.
        }
    })
     res.send("刪除成功");
    //如果刪除成功放在這。。雖然不會阻塞了,但是如果因為某些原因沒有入庫成功- -,臥槽

想過promise async但是實質(zhì)上好像還是一個回調(diào)的語法糖

回答
編輯回答
故人嘆

http://mongoosejs.com/docs/ap...
remove可以看作是實例方法...你需要先實例化一個model.
如果用User這個Model操作應(yīng)該是用findOneAndRemove:http://mongoosejs.com/docs/ap...
異步就是把所有要做的都提前寫好
你可以什么都不做,一直等到數(shù)據(jù)回來,再進行操作(阻塞)
也可以把當數(shù)據(jù)數(shù)據(jù)回來了,怎么處理數(shù)據(jù),怎么處理異常全部想好,然后用回調(diào)函數(shù)處理,
問題當然就是異步中的異步了...比較難看,所以有了各種庫...但是你遇到的問題跟這些無關(guān)

User.findOne(whereStr, function(e, u) {
    if(e)
        ....;
    else {
        console.log(u);
        u.remove(function(e, u) {
            if(e)
                //刪除失敗
            else {
                //成功
                User.findOne(whereStr, function(e, u) {
                    console.log(u) //=> []
                })
            }
        })
    }
})
2017年8月30日 18:51
編輯回答
殘淚

async.parallel([

function(cb){
    db.collection("A").find({//條件A}).toArray(function(docs){
        //回調(diào)A
    })
},
function(cb){
    db.collection("B").find({//條件B}).toArray(function(docs){
        //回調(diào)B
    })
},
function(cb){
    db.collection("C").find({//條件C}).toArray(function(docs){
        //回調(diào)C
    })
}

],function(err,result){

//A,B,C處理結(jié)果

})

2017年10月10日 11:09
編輯回答
卟乖

首先你把res.send("刪除成功");放在外邊是肯定不對的。

2017年8月16日 18:56
編輯回答
耍太極
function removeUser (wherestr) {
    return new Promise((resolve, reject) => {
       setTimeout(() => {
         reject('超時了')
       },5000)
       User.remove(wherestr, function(err, res){
        if (err) {
            reject(err)
        }
        else {
           resolve(res)
        }
    })
}
async function run () {
    let res
    try {
      res = await removeUser({'username' : '什么鬼'})
    } catch(err) {
      console.log(err)
    }
}
run()

隨便寫寫,將就著看看

2017年1月23日 01:07