私のアプリケーションには、ネットワークに並行してアクセスする一連のPromiseがありますが、アプリがフルスピードで実行されていると、ネットワークにアクセスする多くのPromiseが原因でネットワークの速度が低下することがありますが、その方法を制御する方法を知りたいです。並行して多くのアクセスネットワーク。これはコードのサンプルです:
var ids = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 6: 56, 7: 7, 8: 8, 5:6 }; // this is random
Promise.all( Object.keys(ids).map(function(dp){
return new Promise(function(resolve, reject){
http.post({url: addr, form: { data: dp }}, function(err, res, body){
if (err){
reject(err)
}
resolve(body.xx);
});
});
})).then(function(data){
http.post({url: hostAddress, form: { data: data.x }}, function(err, res, body){
......
resolve(body.xx);
});
});
});
}))
ネットワーキングはたくさんあります。同時に2つか3つしか許せなかったらいいのにと思います。ご協力いただきありがとうございます。
同時実行オプションがあるBluebird.map()
を使用して、同時に実行中のリクエストの数を制御できます。
const Promise = require('bluebird');
const http = Promise.promisifyAll(require('http');
var ids = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 6: 56, 7: 7, 8: 8, 5:6 }; // this is random
Promise.map(Object.keys(ids).map(function(dp){
return http.post({url: addr, form: { data: dp }).then(function(body) {
return body.xx;
});
}), {concurrency: 2}).then(function(results) {
// process results here
});
http.post()
参考までにdata.x
、いつを参照するのdata
が配列であるため、2番目で何をしようとしているのか理解できませんでした。このコードは、その2番目で実際に何をしようとしていたかを説明するには少し多すぎる擬似コードだと思いますhttp.post()
。
それ以外の場合は、最初にN個のリクエストを起動し、1つが終了するたびに、もう実行する必要がなくなるまで別のリクエストを起動する独自の同時実行制御をコーディングできます。同時実行制御を手動でコーディングする例を次に示します。
または、次のように自分で書くこともできます。
const http = require('http');
function httpPost(options) {
return new Promise(function(resolve, reject) {
http.post(options, function(err, res, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
});
});
}
// takes an array of items and a function that returns a promise
function mapConcurrent(items, maxConcurrent, fn) {
let index = 0;
let inFlightCntr = 0;
let doneCntr = 0;
let results = new Array(items.length);
let stop = false;
return new Promise(function(resolve, reject) {
function runNext() {
let i = index;
++inFlightCntr;
fn(items[index], index++).then(function(val) {
++doneCntr;
--inFlightCntr;
results[i] = val;
run();
}, function(err) {
// set flag so we don't launch any more requests
stop = true;
reject(err);
});
}
function run() {
// launch as many as we're allowed to
while (!stop && inflightCntr < maxConcurrent && index < items.length) {
runNext();
}
// if all are done, then resolve parent promise with results
if (doneCntr === items.length) {
resolve(results);
}
}
run();
});
}
var ids = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 6: 56, 7: 7, 8: 8, 5:6 }; // this is random
mapConcurrent(Object.keys(ids), 2, function(item, index) {
return httpPost({url: addr, form: {data: item}}).then(function(body) {
return body.xxx;
});
}).then(function(results) {
// array of results here
}, function(err) {
// error here
});
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加