zoukankan      html  css  js  c++  java
  • ES6 Promise对象then方法链式调用

    then()方法的作用是Promise实例添加解决(fulfillment)和拒绝(rejection)状态的回调函数。

    then()方法会返回一个的Promise实例,所以then()方法后面可以继续跟另一个then()方法进行链式调用。

    let p = new Promise((resolve, reject) => {
        setTimeout(resolve, 1000, 'success');
    });
    p.then(
        res => {
            console.log(res);
            return `${res} again`;
        }
    )
        .then(
            res => console.log(res)
        );
    // 连续
    // success
    // success again

    但是前一个then()方法中的回调函数中又可能返回一个Promise实例,这时候后面一个then()方法中的回调函数会等前一个Promise实例的状态发生变化才会调用。

    let p = new Promise((resolve, reject) => {
        setTimeout(resolve, 1000, 'success');
    });
    p.then(
        res => {
            console.log(res);
            return new Promise((resolve, reject) => {
                setTimeout(resolve, 1000, 'success');
            });
        }
    )
        .then(
            res => console.log(res)
        );
    // 相隔1000ms
    // success
    // success
  • 相关阅读:
    Go--指针
    Go--struct
    Go--函数
    Go基础
    流程控制
    Go前言
    变量与常量
    Django(三):HttpRequest和HttpResponse
    Django(二):url和views
    tensorflow(一):图片处理
  • 原文地址:https://www.cnblogs.com/qdlhj/p/12067821.html
Copyright © 2011-2022 走看看