2016-09-04 23 views
1

我的回調地獄航線正常工作......如何重寫回調地獄成諾言?

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

但是我想用承諾。任何幫助,提示?

+0

不止回調地獄你的代碼看起來像一個承諾地獄。 – Redu

回答

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

ES2017已在異步/ 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) } 
})