简体   繁体   中英

How do I chain promises and catch in Node.js

I'm trying to insert a new document based on the request received and here's what I'm trying to do.

var function = (req,callBack)=>{
    queryDB.findOne({query}).then((result)=>{
        return(result); // see if requested object exists in DB and return if yes  
}).then((result)=>{
    if(condition:if required object exists){
        updateDB.updateOne({query}).then((result)=>{ //update required object with new values
            if(condition:update successful){
                ref.function(value).then((k)=>{ // invoke for computation
                    return(k);
                }).then((k)=>{
                    var document = new Document({ //create a new document 
                    ....
                    ....
                    ....
                    ....
                    ....
                    });

                    document.save().then((doc)={
                        callBack(doc); //return new document after successful insert
                    }).catch((err)=>{
                        updateDB.updateOne({query}).then((doc)=>{}) //revert back the update done earlier incase of error while inserting new document
                        callBack(err);
                    });
                }).catch((error)=>{
                    updateDB.updateOne({query}).then((doc)=>{}) //revert back the update done earlier incase of error when invoked function has an error (2)
                    callBack(err);
                })
            }
        }).catch((errorMessage)={
            callBack(errorMessage);
        })
    }else{
        callBack("Required Object Doesn't Exist");
    }
}).catch((errorMessage)=>{
    callBack(errorMessage);
})

}

The behavior I'm expecting is if there is an error in ref.function it should revert the update and send back error message but the API hangs indefinitely without reverting back the update done prior.

While the revert back works fine in-case of error in inserting new document to DB.

Since ref.function(value) is followed by a then with return k , the catch block probably only catches the errors if ref.function rejects the promise and the errors in the block below (after ref.function )

.then((k)=>{ // invoke for computation
   return(k);
})

Try adding Promise.resolve before the ref.function

 return Promise.resolve(
 () => {
   return ref.function(value);
 }).then(
 k => {
    ...
 }).catch(
 err => {
    updateDB.updateOne({query}).then((doc)=>{}) //revert back the update done earlier incase of error when invoked function has an error (2)
    callBack(err);
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM