JavaScript回调方式

异步

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 异步编程对JavaScript语言太重要。Javascript语言的执行环境是“单线程”的,如果没有异步编程,根本...
    呼呼哥阅读 7,334评论 5 22
  • 一.非阻塞和异步 借用知乎用户严肃的回答在此总结下,同步和异步是针对消息通信机制,同步代表一个client发出一个...
    Daniel_adu阅读 1,855评论 0 8
  • 欢迎阅读专门探索 JavaScript 及其构建组件的系列文章的第四章。 在识别和描述核心元素的过程中,我们还分享...
    OSC开源社区阅读 1,164评论 1 10
  • title: promise总结 总结在前 前言 下文类似 Promise#then、Promise#resolv...
    JyLie阅读 12,298评论 1 21
  • 一路走来,和很多人都没了联系,想想时间过得真快,各自有了属于自己的生活轨道,没了交集,所幸还能通过社交平台知道一些...
    浅浅浅笑痕_阅读 129评论 0 0