promise介绍

promise使用

new Promise返回的对象称之为Promise对象

三种状态:
    pending 正在进行
    fulfilled 已完成
    rejected 已失败

1. new Promise 接收一个函数 executor
2. 函数 executor 接收两个参数,resolve,reject
    调用resolve的时候,把promise对象转成成功状态
    调用reject的时候,把promise对象转成失败状态
3. promise对象的then方法来注册成功状态或者失败状态要执行的函数
    p.then(resolveFunc,rejectFunc);
    p.then(resolveFunc,rejectFunc);
    p.then(resolveFunc,rejectFunc);
    p.then(resolveFunc,rejectFunc);

    实现是一个promise对象调用多次then方法

5. then函数的链式操作
    p.then().then().then();

    就是then函数执行后返回一个promise对象

6. thenable
    拥有 then 方法的对象或函数
    {
        then(){}
    }

    promise对象也拥有then方法

7. 当给resolve传入一个promise对象的时候,只有等到promise对象装成成功或者失败,resolve才会成功

8.resovle要接受的参数
    1. 简单值
    2. 接收thenable对象
    
9.then中成功或失败执行的函数的返回值
    1. 有简单类型返回值,作为then方法返回的promise对象的成功状态的值

    2. 当返回一个thenable对象的时候,只有是成功状态才能执行下一个then

基本使用

let p = new Promise((resolve,reject) => {
    setTimeout(function (){
        resolve('成功')	
        //reject('失败')	
    },3000)
})

// 怎么知道p这个对象转成了成功或失败,需要用then来注册成功要执行的函数或失败要执行的函数
p.then(function (data){
    console.log('then第一个参数成功了',data)
},function (){
    console.log('then第2个参数失败了')	
})

p.then(function (data){
    console.log('then第一个参数成功了',data)
},function (){
    console.log('then第2个参数失败了')	
})

p.then(function (data){
    console.log('then第一个参数成功了',data)
},function (){
    console.log('then第2个参数失败了')	
})

setInterval(function (){
    // console.log(p)	
},1000)

then函数的链式操作

let p = new Promise((resolve,reject) => {
    setTimeout(function (){
        resolve('成功了');
    },3000)
});

p
.then(function (data){
    console.log('then第一个参数成功了',data)
    //return 123  // 有返回值,作为then方法返回的promise对象的成功状态的值
    
    // 当返回一个thenable对象的时候,只有是成功状态才能指向下一个then
    return new Promise((resolve) => {
        setTimeout(function (){
            resolve('我是第二个promise对象成功的值')	
        },5000)
    })
})
.then(function (data){
    console.log('第二个then,执行了',data)	
})
.then(function (data){
    console.log('第3个then,执行了',data)	
})

setInterval(function (){
    console.log(p)	
},1000)

resovle要接受的参数

  1. 简单值
  2. 接收thenable对象
// thenable对象
let obj2 = new Promise((resolve,reject) => {
    setTimeout(function (){
        // resolve('p2成功')	
        reject('失败')
    },5000)
})

let obj = {
    then(resolve,reject){
        setTimeout(() => {
            resolve('我完成了')
        },7000)
    }
}


let p = new Promise((resolve,reject) => {
    setTimeout(function (){
        resolve(obj2);
    },3000)
});

p.then(function (data){
    console.log('then第一个参数成功了',data)
},function (){
    console.log('then第2个参数失败了')	
});

setInterval(function (){
    console.log(p)	
},1000)

你可能感兴趣的:(javascript)