동기 API가있는 타사 라이브러리가 있다고 가정합니다. 당연히 비동기식으로 사용하려고하면 "병렬"로 여러 가지 작업을 할 때 차단된다는 의미에서 바람직하지 않은 결과가 발생합니다.Node.js 동기 라이브러리 코드 차단 비동기 실행
이러한 라이브러리를 비동기 방식으로 사용할 수있는 일반적인 패턴이 있습니까?
은 (간결 NPM에서 async 라이브러리를 사용하여) 다음과 같은 예를 생각해var async = require('async');
function ts() {
return new Date().getTime();
}
var startTs = ts();
process.on('exit', function() {
console.log('Total Time: ~' + (ts() - startTs) + ' ms');
});
// This is a dummy function that simulates some 3rd-party synchronous code.
function vendorSyncCode() {
var future = ts() + 50; // ~50 ms in the future.
while(ts() <= future) {} // Spin to simulate blocking work.
}
// My code that handles the workload and uses `vendorSyncCode`.
function myTaskRunner(task, callback) {
// Do async stuff with `task`...
vendorSyncCode(task);
// Do more async stuff...
callback();
}
// Dummy workload.
var work = (function() {
var result = [];
for(var i = 0; i < 100; ++i) result.push(i);
return result;
})();
// Problem:
// -------
// The following two calls will take roughly the same amount of time to complete.
// In this case, ~6 seconds each.
async.each(work, myTaskRunner, function(err) {});
async.eachLimit(work, 10, myTaskRunner, function(err) {});
// Desired:
// --------
// The latter call with 10 "workers" should complete roughly an order of magnitude
// faster than the former.
포크/가입하거나 산란 작업자 프로세스를 수동으로 내 유일한 옵션은?