2015-05-19 18 views
1

我試圖重構回調地獄承諾。 如何使用findById.exec()和object.save()來承諾?如何使用貓鼬原生諾言(mpromise)來查找文檔,然後保存

exports.changeAnimalName = function(req, res) { 
var Animal = mongoose.model('Animal', animalSchema); 

Animal.findById(id, function (err, animal) { 
    if (animal) { 
    animal.name=req.body.name; 
    animal.save(function (err, animalSaved) { 
    if (err) return console.error(err); 
    return res.send(animalSaved); 
    }); 
    } 
}); 
} 
+0

是的,這是真的,這只是一個藉口,看到完整的例子。 – user1458180

回答

5

你可以做這樣的事情:

// No need to import the model every time 
var Animal = mongoose.model('Animal', animalSchema); 

exports.changeAnimalName = function(req, res) { 
    // return the promise to caller 
    return Animal.findById(id).exec().then(function found(animal) { 
    if (animal) { 
     animal.name = req.body.name; 
     return animal.save(); // returns a promise 
    } 

    // you could throw a custom error here 
    // throw new Error('Animal was not found for some reason'); 
    }).then(function saved(animal) { 
    if (animal) { 
     return res.send(animal); 
    } 

    // you could throw a custom error here as well 
    // throw new Error('Animal was not returned after save for some reason'); 
    }).then(null, function(err) { 
    // Could be error from find or save 
    console.error(err); 
    // respond with error 
    res.send(err); 

    // or if you want to propagate the error to the caller 
    // throw err; 
    }); 
} 

另外,您可以使用findByIdAndUpdate把它簡化一下:

var Animal = mongoose.model('Animal', animalSchema); 

exports.changeAnimalName = function(req, res) { 
    // return the promise to caller 
    return Animal.findByIdAndUpdate(id, { 
    name: req.body.name 
    }).exec().then(function updated(animal) { 
    if (animal) { 
     return res.send(animal); 
    } 

    // you could throw a custom error here as well 
    // throw new Error('Animal was not returned after update for some reason'); 
    }).then(null, function(err) { 
    console.error(err); 
    // respond with error 
    res.send(err); 

    // or if you want to propagate the error to the caller 
    // throw err; 
    }); 
} 
+0

超清,謝謝 – user1458180