1.在nodeJS里面使用 node的异步和并发
node默认并发10个,..................
参考:
http://kyfxbl.iteye.com/blog/2009738
js里面的异步:
js 最新版本默认是支持de ,可以使用promice,await,async
async function timeout(ms) { await new Promise((resolve, reject) => { setTimeout(() => { console.log('进入timeout'); resolve() }, ms); }); } async function asyncPrint(value, ms) { console.log(value); await timeout(ms); console.log(value); } asyncPrint('hello world', 3000);
function timeout(ms) { return new Promise((resolve, reject) => { setTimeout(() => { console.log('进入timeout'); resolve() }, ms); }); } async function asyncPrint(value, ms) { console.log(value); await timeout(ms); console.log(value); } asyncPrint('hello world', 3000);
对比两段代码:
async
让函数返回一个promise 对象
await:
修饰符,后面跟一个 promise 对象 ,等待 primise执行 ,
当promise,执行完毕(就是返回 resolve())的时候,执行之后的语句(阻塞作用)
await 必须写在async函数里面
await 后面的表达式不是promise,就会正常执行,不会阻塞
参考:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/await
https://segmentfault.com/a/1190000007535316#articleHeader4