ES6----Promise基本用法

在进行微信小程序开发或者vue项目开发的过程中,经常会遇到ES6中Promise,那么这个该怎么用呢?

1、Promise是什么

Promise是异步编程的一种解决方案,在ES6中Promise被列为了正式规范,统一了用法,原生提供了Promise对象。

2、基础用法

// resolve代表成功 reject失败 都是一个函数
let p = new Promise(function(reslove,reject){
    //reslove('成功')  //状态由等待变为成功,传的参数作为then函数中成功函数的实参
    reject('失败')  //状态由等待变为失败,传的参数作为then函数中失败函数的实参
})

//then中有2个参数,第一个参数是状态变为成功后应该执行的回调函数,第二个参数是状态变为失败后应该执行的回调函数。
p.then((data)=>{
    console.log('成功'+data)
},(err)=>{
    console.log('失败'+err)
})

常见用法:

function read( content ) {
    return new Promise(function( reslove,reject ) {
        setTimeout(function(){
                if(content>4){
                    resolve(content)
                }else{
                    reject('小于4')
                }
        },1000)
    })
}

read(1).then(( data )=>{
    console.log(data)
},( err )=>{
    console.log(err) //小于4
    return read(2) //将状态改为了失败
})
.then(( data )=>{
    console.log('data',data)
},( err )=>{
    console.log(err) //小于4
})

参考:https://www.jianshu.com/p/3023a9372e5f

原文地址:https://www.cnblogs.com/e0yu/p/12743551.html