美文网首页
理解 Javascript 的 异步

理解 Javascript 的 异步

作者: SingleDiego | 来源:发表于2019-08-22 22:47 被阅读0次

    先看下面一个例子:

    const delay = () => {
      setTimeout(() => {
        console.log('hello');
      }, 100);
    };
    
    const atOnce = () => {
      console.log('world');
    };
    
    const test = () => {
      delay();
      atOnce();
    };
    
    test();
    
    
    // 输出结果
    // world
    // hello
    

    delay 函数设定 100 毫秒后输出字符串 hello。在 test 函数中 delay()atOnce 上方。

    但 Javascript 执行时代码并非线性地运行,并不会等待 delay() 执行完毕再去执行 atOnce。所以我们看到先输出 world 再输出 hello




    如果需要等待 delay 函数执行完毕后再执行 atOnce 函数,下面演示几种方法。

    使用 Promise 和 then

    const delay = () => {
      let promise = new Promise((resolve, reject) => {
        setTimeout(resolve('hello'), 100);
      });
      return promise;
    };
    
    const atOnce = () => {
      console.log('world');
    };
    
    delay()
    .then((value) => {
      console.log(value)
    })
    .then(atOnce)
    
    // 输出
    // hello
    // world
    




    使用 Generator

    const delay = () => {
      let promise = new Promise((resolve, reject) => {
        setTimeout(resolve('hello'), 100);
      });
      return promise;
    };
    
    const atOnce = () => {
      console.log('world');
    };
    
    function* gen(){
      yield delay();
      atOnce();
    };
    
    var g = gen();
    var result = g.next();
    
    result.value
    .then((data) => {
      console.log(data)
    })
    .then(() => {g.next()});
    
    // 输出
    // hello
    // world
    




    使用 async 和 await

    const delay = async () => {
      let promise = new Promise((resolve, reject) => {
        setTimeout(resolve('hello'), 100);
      });
      return promise;
    };
    
    const atOnce = () => {
      console.log('world');
    };
    
    const test = async () => {
      const v = await delay();
      console.log(v);
      atOnce();
    }
    
    test()
    
    // 输出
    // hello
    // world
    

    相关文章

      网友评论

          本文标题:理解 Javascript 的 异步

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