JavaScript 异步 setTimeout promise async await

异步在此就不再赘述,下面主要说一下JS中异步的实现方式。

1,setTimeout 计时器 ,实现代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function print() {
            console.log("setTimeOut Run")
        }
        console.log("5秒后之后 print函数,打印:setTimeOut Run")
        setTimeout(print, 5000);
    </script>
</body>
</html>

2,Promise ,简单用法如下:

Promise 构造函(即function (resolve, reject) { // 要做的事情...})数只有一个参数,是一个函数,这个函数在构造之后会直接被异步运行,所以我们称之为起始函数。起始函数包含两个参数 resolve 和 reject。resolve 和 reject 都是函数,其中调用 resolve 代表一切正常,reject 是出现异常时所调用的:

在构造函数中的内容是同步运行。如下

    <script>
        new Promise(function (resolve, reject) {
            console.log("new a promise")
        });
        console.log("last console")
    </script>

运行结果如下:

 显而易见,先执行console.log("new a promise"),然后执行console.log("last console")

Promise,完成结构如下:

Promise().then().catch().finally()

then内开始异步运行,catch 异常捕捉,finaly 整个代码执行完后执行的代码

 <script>
        new Promise(function (resolve, reject) {
            resolve("执行正确")
            reject("执行错误")
        }).then(function(str){
           console.log(str)
        }).catch(function(str){
            console.log(str)
        }).finally(function(){
            console.log("执行完毕")
        });
        console.log("last console")
    </script>

执行结果如下:

 先执行  console.log("last console")

然后执行then,

最后执行 finally。

执行了 resolve 即进入了then,不在执行reject。

如果将resolve和reject换一下位置 ,执行了reject函数 跳到catch 则不会执行 then函数

  <script>
        new Promise(function (resolve, reject) {
            reject("执行错误")
            resolve("执行正确")
        }).then(function(str){
           console.log(str)
        }).catch(function(str){
            console.log(str)
        }).finally(function(){
            console.log("执行完毕")
        });
        console.log("last console")
    </script>

执行结果如下:

由输出结果可以看出,promise中 构造函数是同步执行,进入then或者catch后则是异步执行。

再详细说一下promise的用法:

then可以连续使用,前一个then中的返回值 是下一个then的输入值,请看示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        new Promise(function(resolve,reject){
            resolve("resolvefuc")
        }).then(function(param){
            console.log(param);
            return 7;
        }).then(function(param){
            console.log(param)
        })
        console.log("我后执行,但是我先输出")
    </script>
</body>
</html>

输出结果:

或者 拿到promise对象然后执行then:

 <script>
      var pro=  new Promise(function(resolve,reject){
            resolve("resolvefuc")
        })
        
        pro.then(function(param){
            console.log(param);
            return 7;
        }).then(function(param){
            console.log(param)
        })
        console.log("我后执行,但是我先输出")
    </script>

输出结果:

3,async  用法简单,在定义函数是 函数名称前 加上async关键字即可,async函数返回一个promise,但是此时是同步执行,请看实例代码:

 <script>
      async function print(){
          console.log("async 函数")
      }
      console.log(print())
 </script>

输出结果如下:

由打印结果可以看出,代码是顺序执行的。

函数返回值再调用then即可开始异步执行。

    <script>
      async function print(){
          console.log("async 函数")
      }
      print().then(function(){
        console.log("我在结束后被打印")
      })
      console.log("结束")
    </script>

打印结果如下:

async 和 await 

await 就是等待异步处理完成,然后向下执行代码。

    function testAwait() {
            return new Promise((resolve) => {
                setTimeout(function () {
                    console.log("testAwait");
                    resolve();
                }, 1000);
            });
        }

        async function helloAsync() {
            testAwait();
            console.log("helloAsync");
        }
        helloAsync();

执行结果:

执行结果很明显值先执行

 

  console.log("helloAsync"); 再执行  console.log("restawait");

如果加上await 执行顺序发生变化

执行结果

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值