2018-08-27 10:31:25 373浏览
今天扣丁学堂HTML5前端培训老师给大家介绍一下关于介绍了关于NodeJS实现同步的相关内容,NodeJS被打上了单线程、非阻塞、事件驱动…..等标签。在单线程的情况下,是无法开启子线程的。经过了很久的研究,发现并没有thread函数!!!但是有时候,我们确实需要“多线程”处理事务。nodeJS有两个很基础的api:setTimeout和setInterval。这两个函数都能实现“异步”。nodeJS的异步实现:nodeJS有一个任务队列,在使用setInterval函数的时候,会每隔特定的时间向该任务队列增加任务,从而实现“多任务”处理。但是,“特定的时间”不代表是具体的时间,也有可能是会大于我们设定的时间,也有可能小于。setInterval(function() { console.log(new Date().getTime()); }, 1000);
1490531390640 1490531391654 1490531392660 1490531393665 1490531394670 1490531395670 1490531396672 1490531397675 ......
function a(callback) { // 模拟任务a耗时 setTimeout(function() { console.log("task a end!"); // 回调任务b callback(); }, 3000); }; function b() { setTimeout(function() { console.log("task b end!"); }, 5000); } a(b);
function a(b, c, d) { console.log("hello a"); b(c, d); }; function b(c, d) { console.log("hello b"); c(d); }; function c(d) { console.log("hello c"); d() }; function d() { console.log("hello d"); }; a(b, c, d);
hello a hello b hello c hello d
async = require("async"); a = function (callback) { // 延迟5s模拟耗时操作 setTimeout(function () { console.log("hello world a"); // 回调给下一个函数 callback(null, "function a"); }, 5000); }; b = function (callback) { // 延迟1s模拟耗时操作 setTimeout(function () { console.log("hello world b"); // 回调给下一个函数 callback(null, "function b"); }, 1000); }; c = function (callback) { console.log("hello world c"); // 回调给下一个函数 callback(null, "function c"); }; // 根据b, a, c这样的顺序执行 async.series([b, a, c], function (error, result) { console.log(result); });
hello world b hello world a hello world c [ 'function b', 'function a', 'function c' ]
sleep = function (time) { return new Promise(function () { setTimeout(function () { console.log("end!"); }, time); }); }; console.log(sleep(3000));
Promise { <pending> } end!可以看出来,这里返回了Promise对象,直接输出Promise对象的时候,会输出该对象的状态,只有三种:PENDING、FULFILLED、REJECTED。字面意思很好理解。也就是说Promise有可能能实现我们异步任务同步执行的功能。我们先用Promise+then结合起来实现异步任务同步操作。
sleep = function () { return new Promise(function (resolve, reject) { setTimeout(function () { console.log("start!"); resolve(); }, 1000); }) .then(function () { setTimeout(function () { console.log("end!"); }, 2000); }) .then(function () { console.log("end!!"); }) }; console.log(sleep(1000));
Promise { <pending> } start! end!! end!
display = function(time, string) { return new Promise(function (resovle, reject) { setTimeout(function () { console.log(string); resovle(); }, time) }); }; // 执行顺序:b a c fn = async function () { // 会造成阻塞 await display(5000, "b"); await display(3000, "a"); await display(5000, "c"); }();
b a c
以上就是关于NodeJS如何实现同步的方法示例的全部内容了,希望本文对大家的学习HTML5前端开发有所帮助,扣丁学堂IT职业在线学习教育平台为您提供权威的HTML5开发环境搭建视频,通过千锋扣丁学堂金牌讲师在线录制的HTML5开发教程,让你快速掌握HTML5从入门到精通开发实战技能。扣丁学堂H5技术交流群:559883758。
【关注微信公众号获取更多学习资料】