promise初识

一、什么是promise、其作用是什么

什么是:
Promise是ES6中的一个内置对象,实际是一个构造函数。
作用:
解决回调地狱(回调函数层层嵌套就是回调地狱)
特点:
①三种状态:pending(进行中)、resolved(已完成)、rejected(已失败)。只有异步操作的结果可以决定当前是哪一种状态,任何其他操作都不能改变这个状态。
②两种状态的转化:其一,从pending(进行中)到resolved(已完成)。其二,从pending(进行中)到rejected(已失败)。只有这两种形式的转变。
③Promise构造函数的原型对象上,有then()和catch()等方法,then()第一个参数接收resolved()传来的数据,catch()第一个参数接收rejected()传来的数据

举个栗子

 let pro = new Promise((resolve, reject) => {
    
    
        $.ajax({
    
    
            url: 'http://wkt.shangyuninfo.cn/weChat/applet/course/banner/list?number=4',
            success(res) {
    
    
                resolve(res)
            },
            error(error) {
    
    
                reject(error)
            }
        })
    })
    pro.then((res) => {
    
    
        console.log(res);
        return res.data[0].id
    }).then((res_1) => {
    
    
        console.log(res_1);
    }).catch((error) => {
    
    
        console.log(error);
    })

promise本身不是异步的,里面的then()方法是异步的

Guess you like

Origin blog.csdn.net/qq_52654932/article/details/130350528