Promise


Promise

Promise是ES6异步编程的新解决方案。语法上Promise是一个构造函数,用来封装异步操作并可以获取其成功或失败的结果

js
//实例化 Promise对象
const p = new Promise(function(resolve,reject){
    setTimeout(function(){
        //
        //let data='数据库中的用户数据';
        //resolve
        //resolve(data);
        let err = '数据读取失败';
        reject(err)
    },1000)
	})
	//调用promise对象的then方法
	p.then(function(value){
        console.log(value);
    },function(reason){
        console.error(reason)
    })

Promise封装读取文件

js
//1.引入fs模块
const fs = require('fs')

//2.调用方法读取文件
// fs.readFile('./resources/包含min函数的栈.md',(err,data)=>{
//     //如果失败,则抛出错误
//     if(err) throw err;
//     //如果没有出错,则输出内容
//     console.log(data.toString())
// });

//3.使用Promise封装
const p = new Promise(function (resolve, reject) {
    fs.readFile('./resources/包含min函数的栈.md', (err, data) => {
        //判断如果失败
        if(err) reject(err);
        //如果成功
        resolve(data);

    })
})
p.then(function(value){
    console.log(value.toString())
},function(reason){
    console.log('读取失败!')
})

发送Ajax请求

js
    //接口地址:https://api.apiopen.top/getJoke
    //1.创建对象
    const p = new Promise((resolve,reject)=>{
    const xhr = new XMLHttpRequest();
    //2.初始化
    xhr.open('GET','https://api.apiopen.top/getJoke');
    //3.发送
    xhr.send();
    //4.绑定事件,处理响应结果
    xhr.onreadystatechange = function(){
        //判断
        if(xhr.readyState === 4){
            //判断响应状态码
            if(xhr.status >=200 && xhr.status < 300){
                resolve(xhr.response)
            }else{
                //如果失败
                reject(xhr.status)
            }
        }
    }
})
p.then(function(value){
    console.log(value);
},function(reason){
    console.error(reason)
})

Promise.prototype.then

js
//创建promise对象
const p = new Promise((resolve,reject)=>{
    setTimeout(() => {
        resolve('用户数据')
        // reject('出错啦')
    }, 1000);
})
//调用then方法  then方法的返回结果是Promise对象,对象状态由回调函数的执行结果决定
//1.如果回调函数中返回的结果是 非Promise的属性,状态为成功,返回值为 对象的成功值
// const result = p.then(value => {
//     console.log(value)
//     //1.非 promise 类型的属性
//     //return 123;
//     //2.是 promise对象
//     // return new Promise((resolve,reject)=>{
//     //     // resolve('ok')
//     //     // reject('error')
//     // })
//     //3.抛出错误
//     throw new Error('出错啦!')
// },reason => {
//     console.warn(reason)
// })
//链式调用
p.then(value=>{
    
},reason =>{
}).then(value=>{

},reason=>{})
console.log(result)

catch方法

js
const p = new Promise((resolve,reject)=>{
    setTimeout(() => {
        //设置p对象的状态为失败,并设置失败的值
        reject('出错啦!')
    }, 1000);
})
// p.then(function(value){},function(reason){
//     console.error(reason)
// })
p.catch(function(reason){
    console.warn(reason)
})

文章作者: Daniel Lin
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Daniel Lin !