美文网首页
异步编程(Promise 、async)

异步编程(Promise 、async)

作者: 冷r | 来源:发表于2019-08-15 17:10 被阅读0次

    什么是同步和异步?

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

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

    1. promise

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

    • Promise.try
    • Promise.all
    • Promise.reject
    • Promise.resolve
    • Promise.then
    • Promise.prototype.resolve
    • Promise.prototype.reject
       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 函数是一个状态机,封装了多个内部状态。

    • function 关键字于函数名之间有一个星号
    • 函数体内部使用yield表达式,定义不同的内部状态(yield在英语里的意思就是“产出”)

    注意:

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

    yield与return:

    • 相似之处在于,都能返回紧跟在语句后面的那个表达式的值。
    • 区别在于每次遇到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());
    };
    

    相关文章

      网友评论

          本文标题:异步编程(Promise 、async)

          本文链接:https://www.haomeiwen.com/subject/hvqajctx.html