感谢以上回复。我的问题与使用 rx 而不是 rxjs NPM 模块有关。在我卸载 rx 并安装 rxjs 之后,所有示例都开始按预期使用并发。因此,带有 Promises、Callbacks 和 Native Observables 的 http 并发调用运行良好。
我将它们发布在这里,以防万一有人遇到类似问题并进行故障排除。
基于 HTTP 请求回调的示例:
var Rx = require('rxjs'),
request = require('request'),
request_rx = Rx.Observable.bindCallback(request.get);
var array = [
'https://httpbin.org/ip',
'https://httpbin.org/user-agent',
'https://httpbin.org/delay/3',
'https://httpbin.org/delay/3',
'https://httpbin.org/delay/3'
];
var source = Rx.Observable.from(array).mergeMap(httpGet, 1);
function httpGet(url) {
return request_rx(url);
}
var subscription = source.subscribe(
function (x, body) {
console.log('=====', x[1].body, '======');
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
});
基于承诺的样本:
var Rx = require('rxjs'),
rp = require('request-promise');
var array = ['https://httpbin.org/ip', 'https://httpbin.org/user-agent',
'https://httpbin.org/delay/3',
'https://httpbin.org/delay/3',
'https://httpbin.org/delay/3'
];
var source = Rx.Observable.from(array).mergeMap(httpGet, 1);
function httpGet(url) {
return rp.get(url);
}
var results = [];
var subscription = source.subscribe(
function (x) {
console.log('=====', x, '======');
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
});
原生 RxJS 示例:
var Rx = require('rxjs'),
superagent = require('superagent'),
Observable = require('rxjs').Observable;
var array = [
'https://httpbin.org/ip',
'https://httpbin.org/user-agent',
'https://httpbin.org/delay/10',
'https://httpbin.org/delay/2',
'https://httpbin.org/delay/2',
'https://httpbin.org/delay/1',
];
let start = (new Date()).getTime();
var source = Rx.Observable.from(array)
.mergeMap(httpGet, null, 1)
.timestamp()
.map(stamp => [stamp.timestamp - start, stamp.value]);
function httpGet(apiUrl) {
return Observable.create((observer) => {
superagent
.get(apiUrl)
.end((err, res) => {
if (err) {
return observer.onError(err);
}
let data,
inspiration;
data = JSON.parse(res.text);
inspiration = data;
observer.next(inspiration);
observer.complete();
});
});
}
var subscription = source.subscribe(
function (x) {
console.log('=====', x, '======');
});