NodeJS如何实现同步的方法示例

2020-06-17 06:42:55易采站长站整理

如果有类似于sync的函数能让任务顺序执行就更好了。终于找到了async这个库

$ npm instanll async


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’ ]

上面的基本async模块的实现的如果了解更多关于async模块的使用,可以点击:查看详情

其实nodeJS基本api也提供了异步实现同步的方式。基于Promise+then的实现


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!

在new Promise任务执行完后,调用了resolve才会执行所有的then函数,并且这些then函数是异步执行的。由输出结果可以知道。(如果所有then是顺序执行的应该是end! -> end!!)。但是上述也做到了两个异步任务之间顺序执行了。

不过,还有更加优雅的方式:使用async+await。