Node.js中如何避免阻塞执行操作?
- 内容介绍
- 文章标签
- 相关推荐
本文共计233个文字,预计阅读时间需要1分钟。
使用Node.js阻塞执行,AppUtil.js内容如下:
javascriptconst Fiber=require('fibers');
// 阻塞执行,不影响Node.js其他调用module.exports={ /** * 挂起当前执行,不干扰Node.js其他调用 * @param {number} ms 挂起时长(毫秒) */ _sleep: function(ms) { var fiber=Fiber.current; fiber.run(function() { Fiber.yield(); }); }}
nodejs阻塞执行AppUtil.js: let Fiber = require("fibers"); //阻塞执行,sleep module.exports = { /** * 挂起.阻塞当前执行.不影响nodejs其它调用. * * @param ms {int} 阻塞时长(ms) */ _sleep: function (ms) { var fiber = Fiber.current; setTimeout(function () { fiber.run(); }, ms); Fiber.yield(); }, /** * 阻塞当前执行,并在唤醒后执行回调 * @param ms {int} 阻塞时长(ms) * @param cb {function()} 回调 * 使用示例: * async.waterfall([ function (callback) { console.log('function1... ' + new Date); AppUtil.sleep(5000,()=>{ return callback(null); }); }, function (callback) { console.log('function2... ' + new Date); ModelUtil.find(SupplierProductInfo, {_id: '529126446302'}, ['id', 'companyName'], (err, result)=> { return callback(err, result); }); }, ], function (err, result) { return AppUtil.handleResult(res, err, result); }); */ sleep: function (ms, cb) { Fiber(function () { AppUtil.infoLog(`sleep ${ms}ms.`); //console.log('wait... ' + new Date); AppUtil._sleep(ms); //console.log('ok... ' + new Date); return cb(); }).run(); }, } 使用示例: AppUtil.sleep(5*1000,()=>{ console.log('5秒后执行'); });
本文共计233个文字,预计阅读时间需要1分钟。
使用Node.js阻塞执行,AppUtil.js内容如下:
javascriptconst Fiber=require('fibers');
// 阻塞执行,不影响Node.js其他调用module.exports={ /** * 挂起当前执行,不干扰Node.js其他调用 * @param {number} ms 挂起时长(毫秒) */ _sleep: function(ms) { var fiber=Fiber.current; fiber.run(function() { Fiber.yield(); }); }}
nodejs阻塞执行AppUtil.js: let Fiber = require("fibers"); //阻塞执行,sleep module.exports = { /** * 挂起.阻塞当前执行.不影响nodejs其它调用. * * @param ms {int} 阻塞时长(ms) */ _sleep: function (ms) { var fiber = Fiber.current; setTimeout(function () { fiber.run(); }, ms); Fiber.yield(); }, /** * 阻塞当前执行,并在唤醒后执行回调 * @param ms {int} 阻塞时长(ms) * @param cb {function()} 回调 * 使用示例: * async.waterfall([ function (callback) { console.log('function1... ' + new Date); AppUtil.sleep(5000,()=>{ return callback(null); }); }, function (callback) { console.log('function2... ' + new Date); ModelUtil.find(SupplierProductInfo, {_id: '529126446302'}, ['id', 'companyName'], (err, result)=> { return callback(err, result); }); }, ], function (err, result) { return AppUtil.handleResult(res, err, result); }); */ sleep: function (ms, cb) { Fiber(function () { AppUtil.infoLog(`sleep ${ms}ms.`); //console.log('wait... ' + new Date); AppUtil._sleep(ms); //console.log('ok... ' + new Date); return cb(); }).run(); }, } 使用示例: AppUtil.sleep(5*1000,()=>{ console.log('5秒后执行'); });

