TypeError:promise.then不是函数

时间:2016-08-10 16:57:09

标签: javascript node.js rxjs5

使用Rxjs v5,尝试按顺序运行http.get请求,但收到错误 var http = require('http'); Rx.Observable .from(data) .pairwise() .concatMap(a => { var url = 'http://to/some/api?origins=' + a[0].lat + ',' + a[0].lng + '&destinations=' + a[1].lat + ',' + a[1].lng; return Rx.Observable.fromPromise(http.get(url)); }) .subscribe(item => { console.log(item); }); js代码:

{{1}}

1 个答案:

答案 0 :(得分:2)

节点http.get方法未返回承诺,请参阅here

它实际上使用了一个相当非标准的界面(至少我以前没有真正看到它),所以为了实现这个目的,你需要一个小的自定义解决方案(注意 :这是一个相对天真的实现):

var http = require('http');
function observableGet(options) {
  return new Rx.Observable(subscriber => {
    var subscription = new Rx.Subscription();

    //Create the request
    var request = http.get(options, (res) => {
      //Create a stream for the "end" event
      var done = Rx.Observable.fromEvent(res, 'end');

      //Create a stream for data events
      var s1 = Rx.Observable.fromEvent(res, 'data')
        //Take data events until all have been read
        .takeUntil(done)
        //Gather all the data events into a single object
        .reduce((body, delta) => body + delta, '')
        //Optional: Parse the resulting data object
        .map(x => JSON.parse(x))
        //Start the stream
        .subscribe(subscriber);

      //Register this stream for disposal
      subscription.add(s1);
    });

    //Grab errors from the request and forward them to the error handler
    //of subscriber
    var s2 = Rx.Observable.fromEvent(request, 'error', (e) => { throw e; })
      .subscribe(subscriber);

    //Register for disposal
    subscription.add(s2);

    //Return the parent subscription
    return subscription;
  });
}

然后您可以使用它代替http.get

    Rx.Observable
    .from(data)
    .pairwise()
    .concatMap(a => {
        var url = //...url;
        return observableGet(url);        
    })    
    .subscribe(item => {
        console.log(item);
    });

或者您可以使用返回Promises的库,这可能会让您的生活更轻松,即request-promise