美文网首页js css html
JS异步操作(Promise,async,await)详解

JS异步操作(Promise,async,await)详解

作者: 郝同学1208 | 来源:发表于2022-04-16 10:14 被阅读0次

文章序

Promise,async,await都是ES6新增的用于处理异步操作/异步方法的关键字,建议在阅读本文前先搞清楚JS的单线程,异步同步,事件循环,可以参考我这篇文章
https://www.jianshu.com/p/fca83f1c4702

Promise

Promise可以将异步代码转化成同步代码,then方法中的回调函数只有在resolve之后才会执行

async await

async包裹的函数中必定出现await,await右边跟随 promise,当promise内部代码执行完毕再执行await下面的代码,promise未执行完毕await下面的代码将阻塞

相关代码

<script>
  function getPromiseName() {
    let promiseName = "我是PromiseName";
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("promise has been resolved with message: " + promiseName);
      }, 3000);
    });
  };

  async function getAsyncName() {
    let asyncName = "我是asyncName";
    let res = await new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("promise has been resolved with message: " + asyncName);
      }, 3000);
    });
    console.log(res);
  };

  console.log("开始执行getPromiseName函数!");
  getPromiseName().then(res => {
    console.log(res);
  });
  
  console.log("开始执行getAsyncName函数!");
  getAsyncName();
  console.log("执行后面的代码!");
</script>

打印结果

开始执行getPromiseName函数!
开始执行getAsyncName函数!
执行后面的代码!
promise has been resolved with message: 我是PromiseName
promise has been resolved with message: 我是asyncName

相关文章

网友评论

    本文标题:JS异步操作(Promise,async,await)详解

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