异步编程(Promise 、async)

2019-08-15  本文已影响0人  冷r

什么是同步和异步?

同步(英语:Synchronization),指对在一个系统中所发生的事件(event)之间进行协调,在时间上出现一致性与统一化的现象。说白了就是多个任务一个一个执行,同一时刻只有一个任务在执行。

异步(英语:Asynchronization),指的是让CPU暂时搁置当前请求的响应,处理下一个请求,当通过轮询或其他方式得到回调通知后,开始运行。多线程将异步操作放入另一线程中运行,通过轮询或回调方法得到完成通知,但是完成端口,由操作系统接管异步操作的调度,通过硬件中断,在完成时触发回调方法,此方式不需要占用额外线程。

1. promise

所谓promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果。

   import axios from "axiso"
   const getProductList=()=>{
        //resolve 成功的回调
        //reject  失败的回调
        return new Promise((resolve,reject)=>{
              axios.get("http://localhost:8080/api").then(res=>{
                      resolve(res)
              }).catch(err=>{
                      reject(err)
              })
        })
  }
  getProductList() //返回的是Promise 对象

promise 新建后就会立即执行 .then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行

2. geberator/yield

Generator 函数是一个状态机,封装了多个内部状态。

注意:

  1. yield表达式只能用在 Generator 函数里面,用在其他地方都会报错。(定义的时候就会报错,不会等到next时)
  2. yield表达式如果用在另一个表达式之中,必须放在圆括号里面。
  3. yield表达式用作函数参数或放在赋值表达式的右边,可以不加括号。

yield与return:

  function* helloWorldGenerator() {
      yield 'hello';
      yield 'world';
      return 'ending';
  }

  var hw = helloWorldGenerator();
  hw.next()
  // { value: 'hello', done: false }
  hw.next()
  // { value: 'world', done: false }
  hw.next()
  // { value: 'ending', done: true }
  hw.next()
  // { value: undefined, done: true }

3. async/ await

它就是 Generator 函数的语法糖

    //generator写法
    const fs = require('fs')
    const readFile = function (fileName) {
        return new Promise(function (resolve, reject) {
            fs.readFile(fileName, function(error, data) {
            if (error) return reject(error);
            resolve(data);
            });
        });
    };

    const gen = function* () {
        const f1 = yield readFile('/etc/fstab');
        const f2 = yield readFile('/etc/shells');
        console.log(f1.toString());
        console.log(f2.toString());
    };

    //使用async语法
    const asyncReadFile = async function () {
    const f1 = await readFile('/etc/fstab');
    const f2 = await readFile('/etc/shells');
    console.log(f1.toString());
    console.log(f2.toString());
};
上一篇 下一篇

猜你喜欢

热点阅读