gpt4 book ai didi

javascript - TypeError : promise. then is not a function

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:28 25 4
gpt4 key购买 nike

使用 Rxjs v5,尝试按顺序运行 http.get 请求但出现错误 TypeError: promise.then is not a functionjs代码:

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

最佳答案

Node http.get 方法不返回 promise ,参见 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

关于javascript - TypeError : promise. then is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38879409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com