promise的基本用法

1.什么是promise?

抽象表达:promise是js中进行异步编程的新的解决方案(旧的:纯回调形式)

具体表达:从语法上讲,promise是一个构造函数

       从功能上讲,promise对象用来封装一个异步操作并可以获取其结果

2.promise的状态改变

初始状态:pending:进行中

     fulfilled:成功(通过resolved将pending状态转为fulfilled)

     rejected:失败

只能从pending变为fulfilled或者从pending变为rejected,只有这两种,且一个promise对象只能改变一次(不能说再从filfilled变为pending)

无论变为成功还是失败,都会有一个结果数据

成功的结果数据一般为value,失败的结果数据一般称为reason

3.promise的基本流程

4.promise的基本使用

    // 1.创建一个新的promise对象
    const p = new Promise((resolve,reject) => { //执行器函数
      // 2.执行异步操作任务
      setTimeout(() => {
        const time = Date.now() //如果当前时间是偶数就代表成功,否则代表失败
       // 3.1如果成功了,调用resolve(value)
       if(time % 2 === 0){
         resolve('成功的数据,time=' + time)
       }else{
          // 3.2如果失败了,调用reject(reason)
         reject('失败的数据,time=' + time)
       }
      },1000)  
    })

    p.then(
      value => {  //接收得到成功的value数据 onResolved
        console.log('成功的回调',value)
      },
      reason => { //接收得到失败的reason数据  onRejected
        console.log('失败的回调',reason)
      },
    )

 

posted @ 2020-04-27 10:28  天空003  阅读(220)  评论(0编辑  收藏  举报