如何将回调地狱重写为承诺

how to rewrite callback hell into promise?

本文关键字:重写 承诺 地狱 回调      更新时间:2023-09-26

我的回调地狱路由工作正常…

var myCallbackHell = router.route('/');
myCallbackHell.get(function(req, res, next) {
  bookModel.find({title: "Animal Farm"}).then(function(book) {
    movieModel.find({title: "Intouchables"}).then(function(movie) {
      gameModel.find({title: "The Last of Us"}).then(function(game) {
        res.render('index', {book_found: book, movie_found: movie, game_found: game});
      });
    });
  });
});

然而,我想用承诺。有什么帮助吗?

您可以使用Promise.all并编写相同的内容,如下所示

var promises = [
  bookModel.find({title: "Animal Farm"}),
  movieModel.find({title: "Intouchables"}),
  gameModel.find({title: "The Last of Us"})
];
Promise.all(promises).then(function(values) {
  res.render('index', {book_found: values[0], movie_found: values[1], game_found: values[2]});
}).catch(function(err) {
  // deal with err
});

ES2017有async/await语法

防止诺言地狱

var myCallbackHell = router.route('/');
myCallbackHell.get( async function(req, res, next) {
    var book = await bookModel.find({title: "Animal Farm"})
    var movie = await movieModel.find({title: "Intouchables"})
    var game = await gameModel.find({title: "The Last of Us"})
    res.render('index', {book_found: book, movie_found: movie, game_found: game});
})

您应该捕获错误和拒绝,因此:

router.get('/', async function(req, res, next) {
    try {
        var book = await bookModel.find({title: "Animal Farm"})
        var movie = await movieModel.find({title: "Intouchables"})
        var game = await gameModel.find({title: "The Last of Us"})
        res.render('index', {book_found: book, movie_found: movie, game_found: game}) 
    } catch (e) { next(e) }
})