当前位置 主页 > 服务器问题 > Linux/apache问题 >

    ES6的异步操作之promise用法和async函数的具体使用

    栏目:Linux/apache问题 时间:2019-12-06 15:54

    promise 基本用法

    Promise 对象是一个构造函数,用来生成 Promise 实例。Promise 构造函数接受一个函数作为参数,该函数的两个参数分别是 resolve 和 reject。

    resolve 函数的作用是,在异步操作成功时调用(Promise 对象的状态从 pending 变为 fulfilled),并将异步操作的结果,作为参数传递出去。

    reject 函数的作用是,在异步操作失败时调用(Promise对象的状态从 pending 变为 rejected),并将异步操作报出的错误,作为参数传递出去。

    const funPromise = function(options) {
     return new Promise(function(resolve, reject) {
      if (/* 异步操作成功 */){
       resolve(result);
      } else {
       reject(error);
      }
     });
    }
    

    resolve 函数的参数除了正常的值以外,还可能是另一个 Promise 实例,此时,初始 promise 的最终状态根据传入的新的 Promise 实例决定。

    reject 方法的作用,相当于抛出错误。等同于 throw new Error('error')。

    Promise.prototype.then()

    Promise 实例具有 then 方法,它的作用是为 Promise 实例添加状态改变时的回调函数,即 Promise 实例生成以后,用 then 方法分别指定 fulfilled 状态和 rejected 状态的回调函数。

    funPromise().then(function(result) {
     // fulfilled
    }, function(error) {
     // rejected
    })
    

    then 方法可以接受两个回调函数作为参数。第一个回调函数是 Promise 对象的状态变为 fulfilled 时调用,第二个回调函数是 Promise 对象的状态变为 rejected 时调用。其中,第二个函数是可选的,不一定要提供。这两个函数都接受 Promise 对象传出的值作为参数。

    then 方法返回的是一个新的 Promise 实例(注意,不是原来那个 Promise 实例)。因此可以采用链式写法,即 then 方法后面再调用另一个 then 方法来处理上一个 then 方法中 return 的结果。

    funPromise().then(function(result) {
     return result.data;
    }).then(function(data) {
     // fulfilled
    });
    

    上面的代码使用 then 方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。并且,第一个 then 返回的结果也可以是另一个异步操作的 Promise 对象,这时后一个 then 函数,就会等待该 Promise 对象的状态发生变化,才会被调用。

    funPromise().then(
     (result) => { return funPromise(result); }
    ).then(
     (data) => { /* fulfilled */ },
     (error) => { /* rejected */ }
    );
    

    上面代码中,第一个 then 方法指定的回调函数,返回的是另一个 Promise 对象。这时,第二个 then 方法指定的回调函数,就会等待这个新的 Promise 对象状态发生变化。如果变为 fulfilled,就调用第一个回调函数,如果状态变为 rejected,就调用第二个回调函数。

    Promise.prototype.catch()

    Promise 实例具有 catch 方法,它的作用是为 Promise 实例添加状态改变为 rejected 状态的回调函数,也就是 then 方法的第二个函数的替代写法。

    funPromise().then(function(result) {
     // fulfilled
    }).catch(function(error) {
     // 处理 funPromise 和之前 then 回调函数运行时发生的错误
    });
    

    Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,无论前面有多少个 then 函数,其中的错误总是会被下一个 catch 语句捕获。

    funPromise().then(function(result) {
     return funPromise(result);
    }).then(function(data) {
     // fulfilled
    }).catch(function(error) {
     // 处理前面三个 Promise 产生的错误
    });