打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
13.Promise

Promise介绍

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

  1. Promise构造函数:Promise(excutor){}
  2. Promise.prototype.then方法
  3. Promise.prototype.catch方法
//实例化 Promise 对象const p = new Promise(function(resolve,reject){    setTimeout(function(){        //        let date = '数据库中的用户数据';        //resolve        resolve(data);                let err = '数据读取失败';        reject(err);    },1000);})//调用promise对象的then方法p.then(function(value){    console.log(value);//数据库中的用户数据},function(reason){    console.log(reason);//数据读取失败})

Promise封装读取文件

//1.引入fs模块const fs = require('fs');//2.调用方法读取文件//fs.readFile('./resources/为学.md',(err,data)=>{////判断失败 则抛出错误//  if(err) throw err;//  //如果没有出错,则输出内容//console.log(data.toString());//})//3.使用Promise封装const p = new Promise(function(resolve,reject){    fs.readFile('./resources/为学.md',(err,data)=>{    //判断如果失败        if(err) reject(err);        //如果成功        resolve(data)})})//调用promise对象的then方法p.then(function(value){    console.log(value。toString());},function(reason){    console.log('读取失败');})

Promise封装AJAX

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

Promise.prototype.then方法

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

Promise实践 读取多个文件

//引入fs模块const fs = require('fs');//调用方法读取文件//fs.readFile('./resources/为学.md',(err,data1)=>{    //fs.readFile('./resources/插秧诗.md',(err,data2)=>{        //fs.readFile('./resources/观书有感.md',(err,data3)=>{//let result = data1   '\r\n'   data2   '\r\n'   data3;//console.log(result);        //})    //})//})//使用Promise实现const p = new Promise(function(resolve,reject){    fs.readFile('./resources/为学.md',(err,data)=>{        resolve(data)})})p.then(value=>{    return new Promise(function(resolve,reject){        fs.readFile('./resources/插秧诗.md',(err,data)=>{            resolve([value,data])        })})}).then(value=>{    return new Promise(function(resolve,reject){        fs.readFile('./resources/观书有感.md',(err,data)=>{            //压入            value.push(data);            resolve(value);        })})}).then(value=>{    console.log(value.join('\r\n'));})

Promise.prototype.catch方法

const p = new Promise((resolve,reject)=>{    setTimeout(()=>{        //设置p对象的状态为失败,并设置失败的值        reject('出错了')    },1000)})p.then(value=>{},reason=>{  console.log(reason);})//catch语法糖p.catch(reason){  console.log(reason);})
来源:https://www.icode9.com/content-4-844601.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
复习promise---node
Promise简单使用
JavaScript异步之从promise到await
Puppeteer 系列踩坑日志—4—跨域的几种方式
Node.js基础入门第三天
如何在现代JavaScript中编写异步任务
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服