简体   繁体   English

TypeError:promise.then不是函数

[英]TypeError: promise.then is not a function

Using Rxjs v5, trying to run http.get requests in sequential order but getting error TypeError: promise.then is not a function js code: 使用Rxjs v5,尝试按顺序运行http.get请求但得到错误TypeError: promise.then is not a function js代码:

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

The node http.get method does not return a promise, see here 节点http.get方法不返回promise,请参见此处

It actually uses a rather non-standard interface (at least I haven't really seen it before), so to get this working you need a small custom work-around instead ( note : this is a relatively naive implementation): 它实际上使用了一个相当非标准的界面(至少我以前没有真正看过它),所以要实现这个,你需要一个小的自定义解决方案( 注意 :这是一个相对天真的实现):

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

Then you can use it in place of http.get 然后你可以用它代替http.get

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

Alternatively you could use a library that returns Promises instead, which might make your life easier, ie request-promise 或者,您可以使用返回Promises的库,这可能会让您的生活更轻松,即请求承诺

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM