nodejs阻塞执行 AppUtil.js:let Fiber = require("fibers"); //阻塞执行,sleepmodule.exports = { /** * 挂起.阻塞当前执行.不影响nodejs其它调用. * * @param ms {int} 阻塞时长(ms) */ _sleep: function (ms) { var fiber = Fib
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秒后执行');
});
