Table of contents
The state of the object is not affected by the outside world.
Once the state changes, it will not change, which means that Promise has only one state at any time.
4.1.3 Comprehensive application of ajax
Promise
1 : Define
Promises are a solution to asynchronous programming that can replace traditional solutions - callback functions and events. ES6 unifies usage and provides Promise objects natively. As an object, Promise has the following two characteristics:
-
The state of the object is not affected by the outside world.
The Promise object represents an asynchronous operation and has three states: pending (in progress), fulfilled (successful) and rejected (failed). Only the result of an asynchronous operation can determine which state it is currently in, and no other operation can change this state. This is also the origin of the name Promise, which means "promise" in English, which means that it cannot be changed by other means.
-
Once the state changes, it will not change, which means that Promise has only one state at any time.
There are only two possibilities for changing the state of a Promise object: from pending to fulfilled and from pending to rejected. As long as these two situations occur, the state will be frozen and will not change again, and this result will always be maintained. At this time, it is called resolved.
2 : Three states
Pending status (in progress) Fulfilled status (successful) Rejected status (failed)
Once changed, there is only one state: Pending -> Fulfilled Pending -> Rejected.
3 : Basic usage
Resolve is used to receive the completed status, and reject is used to receive the failed status.
var promise = new Promise(function(resolve,reject){
let flag = true;
if(flag){
resolve('Status: Execution succeeded!');
}else{
reject("Status: Execution failed!");
}
})
promise.then(function(resolve){
console.log(resolve);
},function(reject){
console.log(reject);
})
Description: The then method can accept two callback functions as parameters. The first callback function is called when the state of the Promise object becomes resolved, and the second callback function is called when the state of the Promise object becomes rejected. Both functions are optional and do not have to be provided. They all accept the value passed from the Promise object as a parameter.
4 : simulate asynchronous
Simulate code that is about to happen in the future.
function timeout(ms){
return new Promise(function(relove,reject){
setTimeout(()=>{
console.log('program'+ms+'print after milliseconds!');
},ms);
})
}
timeout(3000);
5 : Execution steps
function timeout(ms){
console.log(2);
return new Promise(function(relove,reject){
setTimeout(()=>{
console.log(3);
relove(4);
},ms);
})
}
console.log(1);
let res = timeout(3000);
res.then(relove=>{
console.log(relove);
})
Explanation: Promise is executed immediately after it is created, so the first output is Promise. Then, the callback function specified by the then method will be executed after all the synchronization tasks of the current script are executed, so 4 is finally output.
courseware code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
// 1:promise的基本语法
const flag = 1;
const mypromise= new Promise((resolve,reject)=>{
//异步请求
if(flag==2){
resolve("成功的数据");
}else{
reject("失败的数据");
}
});
mypromise.then((resolve)=>{//成功的业务逻辑
console.log(resolve);
},(reject)=>{//失败的业务逻辑
console.log(reject);
})
// 2:模拟异步
console.log("1");
const MyPromise = new Promise((resolve,reject)=>{
console.log("2");
setTimeout(()=>{//模拟异步,不是真的异步
console.log("5");
resolve("成功的数据");
},3000);
})
console.log("3");
MyPromise.then((resolve)=>{ //异步:接收Promise的状态
console.log(resolve);
})
console.log("4");
// 总结:promise 只要new 里面的代码会立即执行
let myPomise=new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("成功了")
},3000)
})
myPomise.then((resolve)=>{
console.log(resolve);
}
,(reject)=>{
console.log(reject);
})
</script>
</body>
</html>
Package ajax
const sendajax = function(url){
return new Promise(function(reslove,reject){
//Create object
const o = new XMLHttpRequest();
o.open('GET',url);//initialization
o.send();//send
//Receive state binding event
o.onreadystatechange = function(){
if(o.readyState === 4){ //Identifies the end of sending the request
if(o.status>=200 && o.status<300){//
reslove(o.response);
}else{
reject(o.status);//Failed status code
}
}
}
})
}
let test = sendajax('https://api.apiopen.top/getJoke');
test.then(function(value){
console.log(value);
},function(reason){
console.log(reason);
})
7:Proimse.prototype.then
The Promise instance has a then method, that is, the then method is defined on the prototype object Promise.prototype. Its function is to add a callback function when the state changes to the Promise instance. The first parameter of the then method is the callback function of the resolved state, and the second parameter is the callback function of the rejected state. The parameters are optional.
The then method returns a new Promise instance (note, not the original Promise instance). Therefore, chain writing can be used, that is, another then method is called after the then method. According to this feature we can use the chain method:
function sayhi(){
let mypromise = new Promise(function(resolve,reject){
let str = "hello world";
resolve(str);
})
return mypromise;
}
sayhi().then(function(value){
console.log(value);
return value;
}).then(function(value){
console.log(value+2);
return value;
})
8:Promise.prototype.catch()
The Promise.prototype.catch() method is an alias for .then(null, rejection) or .then(undefined, rejection), which is used to specify a callback function when an error occurs.
let myfun = function(){
let mypromise = new Promise(function(resolve,reject){
reject('error');
})
return mypromise;
}
//Catch when an error occurs
myfun().catch(function(e){
console.error(e);
});
courseware code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
封装
function sendAjax(url){//封装求ajax的地址
return new Promise((resolve,reject)=>{
const ajax = new XMLHttpRequest();
ajax.open("GET",url);//以get方式打开的请求地址
ajax.send();//发送地址
ajax.onreadystatechange = ()=>{
if(ajax.readyState==4){//服务器请求状态
if(ajax.status==200){//http状态码
const data = JSON.parse(ajax.response);
if(data.code==200){//后台接口的状态
resolve(data.lists);
}else{
reject("数据接口请求失败!");
}
}
}
}
})
}
const MyPromise = sendAjax("http://127.0.0.1:8848/web2210/test.json");
MyPromise.then((resolve)=>{
//要么就操作dom
//逻辑处理
//程序的业务逻辑
console.log(resolve);
})
链式写法
function sayHi(){
const MyPormise = new Promise((resolve,reject)=>{
let str = "hello";
resolve(str);
})
return MyPormise;
}
const MyPromise = sayHi();
MyPromise.then((resolve)=>{
console.log(resolve);
return resolve+"2";
}).then((resolve)=>{
console.log(resolve);
})
catch
function sayHi() {
const MyPormise = new Promise((resolve, reject) => {
reject("失败的数据");
})
return MyPormise;
}
sayHi().then((resolve)=>{
},(reject)=>{
console.log(reject);
})
sayHi().catch((e) => {//只抓错误,成功的业务逻辑不需要管理
console.log(e);
})
</script>
</body>
</html>
async and await
The combination of async and await can make asynchronous code look like synchronous code.
4.1.1 async functions
async is a modifier. The function defined by async will return the value of a Promise object resolve by default, so the then operation can be performed directly on the async function, and the returned value is the incoming function of the then method.
Example:
async function fn(){
//1. If a non-Promise object is returned, the result returned by fn() is a Promise object in a successful state, and the value is the return value
//2. If a Promise object is returned, the result returned by fn() is consistent with the result of the internal Promise object
//3. If an error is returned, fn() returns a Promise object in a failed state
return new Promise((resolve,reject)=>{
resolve('successful data');
});
}
const result = fn();
result.then(
value=>{
console.log(value) //successful data
},reason=>{
console.log(reason) //Failed data
})
4.1.2 await expressions
It is also a modifier . The await keyword can only be placed inside the async function . The function of the await keyword is to obtain the content returned in the Promise , which is the resolve value in the Promise function.
1: await must be placed in the async function
2: The expression on the right side of await is generally a promise object
3: What await can return is the successful value of the promise on the right side
4: If the promise on the right side of await fails, an exception will be thrown, which needs to be captured and processed by try...catch
Example:
const bbb = function(){ return 'string'}
async function funAsy() {
const a = await 1
const b = await new Promise((resolve, reject)=>{
setTimeout(function(){
console.log('b executed')
resolve('time')
}, 3000)
})
const c = await bbb()
console.log(a, b, c)
}
funAsy() // The running result is 3 seconds later, output 1, time , string
If Promise does not add await, 1 string will be output immediately, and after 3 seconds, input: "b is executed".
4.1.3 Comprehensive application of ajax
function sendAjax(url) {
return new Promise((resolve, reject) => {
//Create object
const x = new XMLHttpRequest();
//initialization
x.open('GET', url);
//send
x.send();
// time binding
x.onreadystatechange = () => { //state after onreadystatechange callback
if (x.readyState === 4) {
if (x.status >= 200 && x.status < 300) {
//success
resolve(x.response)
} else {
//fail
reject(x.status)
}
}
}
// readyState state description:
// 0: The proxy is created, the open() method is not called;
// 1: The open method has been called
// 2: send() method one call
// 3: responseText already has a value in LOADING data download
// 4: The download operation is complete
// status: return the web page status, 200~299 are normal status, 404 not found.
})
}
//async and await test
async function main() {
let result = await sendAjax("https://api.apiopen.top/getJoke")
mytext = JSON.parse(result);
console.log(mytext.result[0].sid,mytext.result[0].text);
}
main()
courseware code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
// 1:async的用法
async function myfun(){
// 1:返回非promise对象 那么这个函数返回的就是promise对象成功的状态
// return "succ";
// 2:返回的是promise对象,那么这个函数返回的promise对象与内部一致
return new Promise((resolve,reject)=>{
reject("error");
})
}
const MyPromise = myfun();
MyPromise.then((resolve)=>{
console.log(resolve);
},(reject)=>{
console.log(reject);
})
2:async和await用法
await 修饰的Promise 返回值 是成功的值
await 等待的意思
async function demo(){
try{
const a = 1;
const b = await new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log("promise执行了...");
resolve("error");//成的值
},3000)
})
const c = 3;
console.log(a,b,c);
}catch(e){
console.log(11);
}
}
const MyPromise = demo();
封装
function sendAjax(url){//封装求ajax的地址
return new Promise((resolve,reject)=>{
const ajax = new XMLHttpRequest();
ajax.open("GET",url);//以get方式打开的请求地址
ajax.send();//发送地址
ajax.onreadystatechange = ()=>{
if(ajax.readyState==4){//服务器请求状态
if(ajax.status==200){//http状态码
const data = JSON.parse(ajax.response);
if(data.code==200){//后台接口的状态
resolve(data.lists);
}else{
reject("数据接口请求失败!");
}
}
}
}
})
}
async function getInfo(){
const data = await sendAjax("http://127.0.0.1:8848/web2210/test.json");
//下面的代码依赖data
console.log(data);
}
getInfo();
</script>
</body>
</html>