我正在尝试使用bluebird promises库从trello API获取不同的数据块。在我的快递路由器中,我使用的是中间件isLoggedIn
和getBoards
,它的主体看起来像:
trello.get("/1/members/me/boards") // resolves with array of board objects
.each((board) => {
// do some async stuff like saving board to db or other api calls, based on retrieved board
.catch(err => console.error('ERR: fetching boards error - ${err.message}'))
})
问题是:我想在检索并保存所有电路板时重定向(res.redirect('/')
) 。我怎样才能做到这一点?我应该在哪里放置x res.redirect('/')
表达式?
答案 0 :(得分:1)
我认为你需要这样的东西:
var Promise = require('bluebird');
var promises = [];
trello.get("/1/members/me/boards") // resolves with array of board objects
.each((board) => {
//
promises.push( /*some promisified async call that return a promise, saving data in db or whatever asynchronous action. The important bit is that this operation must return a Promise. */ );
});
//So now we have an array of promises. The async calls are getting done, but it will take time, so we work with the promises:
Promise.all(promises).catch(console.log).then( function(results){
/*This will fire only when all the promises are fullfiled. results is an array with the result of every async call to trello. */
res.redirect('/'); //now we are safe to redirect, all data is saved
} );
编辑:
实际上,您可以使用map而不是每个来避免一些样板代码:
trello.get("/1/members/me/boards") // resolves with array of board objects
.map((board) => {
return somePromisifiedSaveToDbFunction(board);
}).all(promises).catch(console.log).then( function(results){
res.redirect('/');
} );