Javascript 内部沟通方法

  • Callback
  • Event
  • Promise
  • Async/await (node)
  • Reactive

参考

Callback (回调)

1
2
3
4
5
6
var friends = ["Mike", "Stacy", "Andy", "Rick"];

friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName);
// 1. Mike, 2. Stacy, 3. Andy, 4. Rick​
});

Event

一个 event 库

1
2
3
4
5
6
7
8
9
10
11
12
13

ee = new EventEmitter()

function listener1() {
console.log('ONE');
}

function listener2() {
console.log('TWO');
}

ee.addListeners('foo', [listener1, listener2]);
ee.emitEvent('foo');

Promise

下面是个流程
promise 流程
mozilla 文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…

if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});

promise
.then((a)=>{
return a
})
.then((a)=>{ // then 链子 来代替 callback hell
return a
})

promise.catch((error)=>{
console.log(error)
})

Async / Await

c# 的语法.

参考

1
2
3
4
5
6
7
8
9
10
async function asyncFun () {
var value = await Promise
.resolve(1)
.then(x => x * 3)
.then(x => x + 5)
.then(x => x / 2);
return value;
}
asyncFun().then(x => console.log(`x: ${x}`));
// <- 'x: 4'

Reactive

前几个月谢了一篇关于 reactive 的文章. reactive 像 event 和 promise then 链子的结合.