企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
Promise是ES6引入的异步编程的新解决方案。语法上Promise是一个构造函数,用来封装异步操作并可以获取其成功或失败的结果。 1) Promise构造函数: Promise (excutor) {} 2) Promise.prototype.then方法: 执行resolve()方法时执行此函数 3) Promise.prototype.catch方法 语法: **Promise (callback).then(SuccessCallback,errorCallback).catch(errorCallback)** ``` const p=new Promise(function(resolve, reject){ let data="有效数据" let err="数据错误"; if(data=="有效数据"){ resolve(data); }else{ reject(err); } }) p.then(function(value){ console.log(value); }, function(reason){ console.err(reason); }) ``` 示例:node读取文件按 ``` const fs=require("fs"); fs.readFile("./xxx.txt",(err,data)=>{ if(err) throw err; cosole.log(data.toString()); }) //使用Promise封装 const p=new Promise(function(resolve,reject){ fs.readFile("./xxx.txt",(err,data)=>{ if(err) reject(err); resolve(data); }) }) p.then(function(value){ cosole.log(value.toString()); }, function(reason){ console.log("读取失败!") }) ``` Promise封装ajax ``` const p=new Promise(function(resolve,reject){ var xhr=new XMLHttpRequest(); xhr.open("GET","https://api.apiopen.top/getJoke"); xhr.send(); //绑定事件,处理响应结果 xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status>=200 && xhr.status<300){ //console.log(xhr.response); resolve(xhr.response); }else{ reject(xhr.status); } } } }); p.then(function(value){ console.log(value); },function(reason){ console.error(reason); }) ``` then()的返回值是Promise对象,所以可以链式调用! ``` const p =new Promise(function(resolve, reject){ setTimeout(function(){ resolve("数据"); },1000) }) //then()返回的是Promise对象.这个对象的状态由回调函数执行结果决定 //如果回调函数返回的是非promise类型的属性,状态成功,返回值为对象的成功的值 //返回Promise对象时,返回的Promise对象决定对象状态值 var res=p.then(function(value){ console.log(value); }) console.log(res); //[[PromiseStatus]]:"resolved" //[[PromiseValue]]:undefined var res=p.then(function(value){ console.log(value); return 123; }) console.log(res); //[[PromiseStatus]]:"resolved" //[[PromiseValue]]:123 var res=p.then(function(value){ console.log(value); return new Promise(function(resolve,reject){ resolve("ok"); }) }, function(reason){ console.err(reason); }) console.log(res); //[[PromiseStatus]]:"resolved" //[[PromiseValue]]:ok var res=p.then(function(value){ console.log(value); return new Promise(function(resolve,reject){ reject("error"); }) }, function(reason){ console.err(reason); }) console.log(res); //[[PromiseStatus]]:"rejected" //[[PromiseValue]]:"error" var res=p.then(function(value){ console.log(value); //throw new Error("error"); throw "error"; }, function(reason){ console.err(reason); }) console.log(res); //[[PromiseStatus]]:"rejected" //throw new Error("error");对应[[PromiseValue]]:"Error: error at http://127.0.0.1:8848/javascript/demo.html:73:8 at <anonymous>" //throw "error";对应[[PromiseValue]]:"error" ``` catch() ``` const p =new Promise(function(resolve, reject){ setTimeout(function(){ reject("error"); },1000) }) //then接受错误 p.then(function(resolve,reject){ },function(reason){ console.warn(reason) }) //catch接受错误(更简洁) p.catch(function(reason){ console.warn(reason) }) ```