如何使用Bluebird promisification与generator + parallel promises

时间:2015-03-09 06:20:02

标签: arrays generator bluebird koa co

尝试使用蓝鸟以及生成器的koa发出多个请求到beats api。

阅读完一些文档后,我认为以下内容可行

var request = require('co-request'),
  _ = require('lodash'),
  Promise = require('bluebird');
  request = Promise.promisifyAll(request);

module.exports.getTracks = function *tracks(){    
    firstCall = yield makeAPICall('users/' + me + '/mymusic/tracks?limit=150');
      total = firstCall.body.info.total;
      total -= 150;
      tracks = firstCall.body.data;

      //Beats only allows a maximum of 150 tracks per call
      //If more tracks are needed then the remainder is called in sets of 150
      var offset = 150;
        while (total > 0) {
          promises.push(makeAPICall('users/' + me + '/mymusic/tracks?limit=150&offset=' + offset));
          offset += 150;
          total -= 150;
        }

    var responses = yield(Promise.all(promises));
}

    function makeAPICall (query){
      var authOptions = {
        url: 'https://partner.api.beatsmusic.com/v1/api/' + query,
        headers: { 'Authorization': 'Bearer ' + accessToken },
        json: true
      };
      return request.get(authOptions);
    }

方法makeAPI调用按预期与firstCall一起使用,但出于某种原因,当我开始将makeAPICall方法放入数组时,它们似乎永远不会执行。变量响应只产生一系列函数,而不是来自beats api的响应数组。我需要更改什么才能使响应返回类似于firstCall的对象数组?

1 个答案:

答案 0 :(得分:2)

你使用的共同请求已经将回调转换为thunk,所以没有必要尝试宣传。

这是一个简化的可运行示例,类似于您的代码,显示了如何与Koa并行运行api调用(在引擎盖下使用co)。
当你产生一个数组时,co将并行运行任何thunk / promises / generator等。

var request = require('co-request'),
    co      = require('co');

co(function *(){
  var results = yield getTracks();
  results.forEach(function(result){
    console.log(result.body);
  })
}).then();

function * getTracks () {
  var queries = [];
  // swap out your queries here
  queries.push(makeAPICall('5185415ba171ea3a00704eed'));
  queries.push(makeAPICall('54fdc3c9862a3aab01dc95cf'));
  queries.push(makeAPICall('54fdc3da862a3aa501dc95d0'));
  // yielding an array returns an array of results
  var results = yield queries;
  return results;
}

function makeAPICall (query) {
  var options = {
    url: 'http://www.mocky.io/v2/' + query,
    json: true
  }
  return request.get(options)
}