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) {
      // 处理前两个回调函数的错误
    });
    
  • 相关阅读:
    LA 2038 Strategic game(最小点覆盖,树形dp,二分匹配)
    UVA 10564 Paths through the Hourglass(背包)
    Codeforces Round #323 (Div. 2) D 582B Once Again...(快速幂)
    UVALive 3530 Martian Mining(贪心,dp)
    UVALive 4727 Jump(约瑟夫环,递推)
    UVALive 4731 Cellular Network(贪心,dp)
    UVA Mega Man's Mission(状压dp)
    Aizu 2456 Usoperanto (贪心)
    UVA 11404 Plalidromic Subsquence (回文子序列,LCS)
    Aizu 2304 Reverse Roads(无向流)
  • 原文地址:https://www.cnblogs.com/lyzz1314/p/13396637.html
Copyright © 2011-2022 走看看