【问题标题】:how to rewrite callback hell into promise?如何将回调地狱重写为承诺?
【发布时间】:2018-01-24 16:43:35
【问题描述】:

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

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。任何帮助,提示?

【问题讨论】:

  • 不仅仅是回调地狱,您的代码看起来更像是一个承诺地狱。

标签: javascript callback promise


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    ES2017 有 async/await 语法

    为了防止Promise地狱

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

    【讨论】:

      猜你喜欢
      • 2014-06-21
      • 2016-08-30
      • 2020-12-24
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2021-04-16
      • 1970-01-01
      相关资源
      最近更新 更多