【发布时间】:2013-11-28 04:22:56
【问题描述】:
假设您有一个具有同步 API 的第 3 方库。自然,尝试以异步方式使用它会产生不良结果,因为您在尝试“并行”执行多项操作时会被阻止。
是否有任何通用模式允许我们以异步方式使用此类库?
考虑以下示例(为简洁起见,使用 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.
是我唯一的选择吗?
【问题讨论】:
标签: node.js asynchronous blocking nonblocking synchronous