Distal asynchronous process (King pesticides chicken Ace)
- Traditional native asynchronous
- Callback
- event
- Using asynchronous workflow tools (others packaged stuff) (*****)
- es6 Promise
Promise 是异步编程的一种解决方案,比传统的解决方案–回调函数和事件--更合理和更强大。它由社区最早提出和实现,ES6将其写进了语言标准,统一了语法,原生提供了Promise
所谓Promise ,简单说就是一个容器,里面保存着某个未来才回结束的事件(通常是一个异步操作)的结果。从语法上说,Promise是一个对象,从它可以获取异步操作的消息。
Promise 对象的状态不受外界影响
三种状态:
pending:进行中
fulfilled :已经成功
rejected 已经失败
状态改变:
Promise对象的状态改变,只有两种可能:
从pending变为fulfilled
从pending变为rejected。
这两种情况只要发生,状态就凝固了,不会再变了,这时就称为resolved(已定型)
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('任务二')
}, 2000)
}).then(data => {
return data
})
Promise.all([p1,p2,p3]).then(function(results){//Promise中all方法将所有Promise对象输出再执行then
console.log(results);
});
Promise.race([p1, p2]).then(///Promise中race方法将最快的其一Promise对象输出再执行then
(result) => {
console.log(result)
}
- es6 generator function
- es6 (7) async function
/*
async函数
es6提供
配合关键字 await使用
await 表示,等待,任务一执行结束之后,才会执行任务二
*/
async function fn () {
const result = await '任务一'
console.log( result )
console.log( '任务二' )
}
fn()
const fn1 = async () => {
const res = await '任务3'
console.log( res )
console.log( '任务四' )
}
fn1()
- node.js in nextTick setImmudiate
nextTick()的回调函数执行的优先级要高于setImmediate();
process.nextTick()属于idle观察者,setImmediate()属于check观察者.在每一轮循环检查中,idle观察者先于I/O观察者,I/O观察者先于check观察者.
在具体实现上,process.nextTick()的回调函数保存在一个数组中,
setImmediate()的结果则是保存在链表中.
在行为上,process.nextTick()在每轮循环中会将数组中的回调函数全部执行完.
而setImmediate()在每轮循环中执行链表中的一个回调函数.
nextTick > 回调函数 > setImmediate
- Third-party library async.js
Summary:
asynchronous processes asynchronous task is placed in the queue, the queue only take asynchronous execution after executing the main thread