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

时间:2016-09-04 16:30:58

标签: javascript callback promise

我的回调地狱路线运作良好......

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});
      });
    });
  });
});
但是,我想使用诺言。任何帮助,提示?

2 个答案:

答案 0 :(得分:3)

您可以使用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
});

答案 1 :(得分:0)

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) }
})