Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

异步编程 #43

Open
conan1992 opened this issue Jul 1, 2020 · 0 comments
Open

异步编程 #43

conan1992 opened this issue Jul 1, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

conan1992 commented Jul 1, 2020

回调函数

fs.readFile('xxx', (err, data) => {

});
  • 缺点
    多层嵌套,形成“回调地狱”,代码可读性和可维护性差;而且如下面读取文件来说,如果其中某个文件读取失败,还要做失败处理,复杂程度可想而知...
fs.readFile('1.json', (err, data) => {
    fs.readFile('2.json', (err, data) => {
        fs.readFile('3.json', (err, data) => {
            fs.readFile('4.json', (err, data) => {

            });
        });
    });
});

事件监听

f1.on('done', f2);
function f1(){

    setTimeout(function () {

      // f1的任务代码

      f1.trigger('done');

    }, 1000);

  }

发布订阅模式

let pubSub = {
  subs: [],
  subscribe(key, fn) { //订阅
    if (!this.subs[key]) {
      this.subs[key] = [];
    }
    this.subs[key].push(fn);
  },
  publish(...arg) {//发布
    let args = arg;
    let key = args.shift();
    let fns = this.subs[key];
 
    if (!fns || fns.length <= 0) return;
 
    for (let i = 0, len = fns.length; i < len; i++) {
      fns[i](args);
    }
  },
  unSubscribe(key) {
    delete this.subs[key]
  }
}
 
//测试
pubSub.subscribe('name', name => {
  console.log(`your name is ${name}`);
})
pubSub.subscribe('gender', gender => {
  console.log(`your name is ${gender}`);
})
pubSub.publish('name', 'leaf333');  // your name is leaf333
pubSub.publish('gender', '18');  // your gender is 18

Promise

链式调用规避了大量的嵌套,复合线性思维;

function readFile( url ){
      return new Promise((resolve)=>{
        var img = new Image();
        img.src = url;
        img.onload = ()=>{
          resolve(img)
        }
      })
    }
    readFile("./test.jpg").then(data => {
      return readFile("./test1.jpg")
    }).then(data => {
      return readFile("./test2.jpg")
    }).then(data => {
      return readFile("./test3.jpg")
    })

async + await

这是 ES7 中新增的关键字,凡是加上 async 的函数都默认返回一个 Promise 对象,而更重要的是 async + await 也能让异步代码以同步的方式来书写,而不需要借助第三方库的支持。

function readFile( url ){
      return new Promise((resolve)=>{
        var img = new Image();
        img.src = url;
        img.onload = ()=>{
          console.log(img)
          resolve(img)
        }
      })
    }
    const readFileAsync = async function () {
      const f1 = await readFile('./test.jpg')
      const f2 = await readFile('./test1.jpg')
      const f3 = await readFile('./test2.jpg')
      const f4 = await readFile('./test3.jpg')
    }
    readFileAsync()
function readFile( url ){
      return new Promise((resolve)=>{
        var img = new Image();
        img.src = url;
        img.onload = ()=>{
          console.log(img)
          resolve(img)
        }
      })
    }
    async function foo(){
      for(var i=1;i<4;i++){
        await readFile("./test"+i+".jpg");
      }
    }
    foo()

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant