异步
1.事件实现异步
class Eventer {
map = null;
constructor() {
this.map = {};
}
add(name, fn) {
if (this.map[name]) {
this.map[name].push(fn);
return;
}
this.map[name] = [fn];
return this; //返回实例,实现链式调用
}
emit(name, ...args) {
this.map[name].forEach(fn => {
fn(...args);
});
return this;
}
}
let e = new Eventer();
e.add("hello", (err, name) => {
if (err) {
console.log(err);
return;
}
console.log(name);
}).emit('hello', '发生了错误').emit('hello', null, "hello node.js");
2.观察者模式
function create(
fn: (param: IObserverParam) => void
): (param: IObserverParam) => (param: IObserverParam) => void {
let ret = false;
return ({ next, complete, error }) => {
function nextFn(...args) {
if (ret) {
return;
}
next(...args);
}
function completeFn(...args) {
complete(...args);
ret = true;
}
function errorFn(...args) {
error(...args);
}
fn({ next: nextFn, complete: completeFn, error: errorFn });
return () => (ret = true);
};
}
interface IObserverParam {
next: Function;
complete: Function;
error: Function;
}
let observer = create(observer => {
setTimeout(() => {
observer.next(1);
}, 1000);
observer.next(2);
observer.complete(3);
});
const subject: IObserverParam = {
next: value => {
console.log(value);
},
complete: console.log,
error: console.log
};
var unsubscribe = observer(subject);
3.promise异步
const getName = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("nodejs");
}, 1000);
});
getName.then(res => {
console.log(res);
});
Promise.all([getName,getName]).then(console.log).catch(console.log);
Promise.race([getName,getName]).then(console.log).catch(console.log);
4.async/await
async function func(s: string) {
return s;
}
// 或者
function func(s: string) {
return Promise.resolve(s);
}
function log(res) {
console.log(res);
return res; // 继续返回promise
}
func("a")
.then(log) // a
.then(log) // a
.then(log) // a
.then(log); // a