使用 bluebird promises 和 express 进行 API 调用

using bluebird promises with express to make API calls

我正在尝试使用 bluebird promises 库从 trello API 获取不同的数据块。在我的 express 路由器中,我使用了中间件 isLoggedIngetBoards,它的主体类似于:

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('/')) 只有 所有 板被检索并保存时。我怎样才能做到这一点?我应该在哪里放置 xres.redirect('/') 表达式?

我想你需要这样的东西:

    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 而不是 each 来避免一些样板代码:

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('/'); 
} );