zoukankan      html  css  js  c++  java
  • 理解JS中的Promise对象

    1. promise是异步编程的一种解决方法

    promise对象代表一个异步操作,有三种状态,pending(进行中)、fulfilled(已成功)、rejected(已失败)
    Promise对象是一个很神奇的东西, 究竟有哪些神奇呢?

    1. 怎么用

    基本用法

    instance = new Promise(function(resolve, reject){
               ...
               //when things goes right:
               resolve(value);
               ...
               //when things goes wrong:
               reject(error);
    })
    

    说明:

    • promise表示的是一个异步操作,每当我们new一个promise实例,就表示一个具体的异步操作

    • 这个异步操作的结果就只能有两种状态:成功/失败,两者都需要回调函数resolve/reject返回。所以不能用return返回结果,而是用resolve(res)将结果返回.
      所以可以用一下两种方式来调用Promise返回的结果:

    • promiseInstance.then((res)=>{console.log(res)});也就是在.then()中调用

    +async function funName(){res = await promiseInstance; console.log(res)}也就是在异步函数中, 调用返回值.

    promise实例生成以后,可以用一个叫做then()方法来分别指定resolved状态和rejected状态的回调函数

    instance.then( //注意, instance这个Promise对象默认向then中传入两个参数(分别是promise中的value&error), 在这里我们使用两个函数来进行处理

        function(value){
            process(value);
        }
        function(error){ // 可选
            process(error);
        }
    )
    

    说明:

    • then方法可以链式回传, 每个.then()中可以处理一个异步对象(如Promise), 仅当异步对象处理完毕之后, 才会向下一个then进行
    • 需要注意的一点就是,then方法返回的是一个新的Promise实例(注意,不是之前的Promise实例),因此可以采用链式写法,即then方法之后再调用另一个then方法

    promise实例生成以后,还有一个叫做catch()的方法来抛出错误异常.catch 其实是 .then(undefined, () => {}) 的语法糖

    Promise 对象的错误具有"冒泡"性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个 catch 语句捕获。

    getJSON("/post/1.json").then(function(post) {
      return getJSON(post.commentURL);
    }).then(function(comments) {
      // some code
    }).catch(function(error) {
      // 处理前两个回调函数的错误
    });
    
  • 相关阅读:
    Splay专题总结
    UVa12657
    ZOJ3772
    POJ1743
    高斯消元模板
    python使用chrom登陆微博
    mysql常用数据库(表)命令
    mysql索引
    mysql建表的时候,时间戳的选用
    php 金额每三位添加一个逗号
  • 原文地址:https://www.cnblogs.com/lyzz1314/p/13396637.html
Copyright © 2011-2022 走看看