测试

<script type="text/javascript">

    function runAsync(){
        var p = new Promise(function(resolve, reject){
            //做一些异步操作
            setTimeout(function(){
                console.log('执行完成');
                reject('出错了');
                resolve('随便什么数据');
            }, 1000);
        });
        return p;
    }
    
    runAsync().then(data => {
        setTimeout(function(){
            console.log(data);
        }, 1000);
    }).catch(data => {
        setTimeout(function(){
            console.log(data);
        }, 1000);
    });
    
    //这是对map的操作,跟promise无关,我只是临时在这里做了个测试
    var mapArr = [1, 2, 3, 4].map(x => x*2);
    console.log(mapArr);

</script>

1.用setTimeout模拟异步耗时

2.如果reject在resolve之前被调用,那么就会抛出异常;否则走正常流程。

3.正常走then,异常走catch

4.有必要解释reject和resolve的作用:reject是往外抛出异常,reject中的参数就是异常信息,会被catch捕获到;resolve是执行成功的意思,resolve中的参数会被传递到then中。

相关文章:

  • 2021-08-07
  • 2021-07-22
  • 2021-05-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-27
猜你喜欢
  • 2021-12-06
  • 2022-12-23
  • 2021-09-14
  • 2021-09-06
  • 2021-12-27
  • 2022-12-23
  • 2018-03-26
相关资源
相似解决方案