What is the Promise
Es6 is an asynchronous solution to es5’s traditional asynchronous solution (callback functions), which provides Promise objects
The way asynchrony was handled in the past
F2 waits for f1 to finish executing
function f1(callback){
setTimeout(() = >{
var res = 'f1'
console.log('I got f1 from the background.');
callback(res)
},1000)}function f2(value){
console.log(value);
}
f1(f2)
Copy the code
Basic usage
const promise = new Promise(function(resolve,reject){
setTimeout(() = >{
var flag = false;
flag ? resolve('success') : reject('failure')},1000)
})
promise.then(
(res) = >{console.log(res)},
(res) = >{console.log(res); })Copy the code
It will be carried out immediately
// Promise will be executed immediately after it is created
const promise = new Promise(function(resolve,reject){
console.log('promise');
resolve()
})
promise.then(function(){
console.log('resolve');
})
console.log('hello');
Copy the code
With native Ajax implementation cases
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title> Peomise case </title> </head> <body> <script> const getJson = function (url) { return new Promise(function (reslove, Reject) {const Handel = function () {// If (this.readystate! == 4) {return} if (this.status === 200) {// Reject (new) {// Reject (new) {// Reject (new) Error(this.statusText)) } } const client = new XMLHttpRequest() client.open("GET", url) client.onreadystatechange = handel client.responseType = 'json' client.setRequestHeader('Accept', "Application/json") to the client. The send ()})} getJson (` ` http://127.0.0.1:2000/name. Then, after obtaining the results / / / / to the success of dad first id is passed to the background The background returns the name of the corresponding character weapon based on the ID (res) => {console.log(res); Const id = res. Data [2]. The id return getJson (` http://127.0.0.1:2000/wepon? id=${id}`) } ).then((res) => { console.log(res) }) </script> </body> </html>Copy the code
Promise.then()
The.then method is a promise.prototype defined on a prototype. Then returns a new Promise object
Promise.catch()
// Promise eats up errors
// It is recommended to use a catch after a promise
const say = function(){
return new Promise(function(resolve,reject){
resolve(v+2)
})
}
say().then(() = >{
console.log('I was processed.');
}).catch(
(error) = >{
console.log(error)
return '123'
}
).then((res) = >{
console.log(res);
})
Copy the code
Promise.all()
// Promise.all
// Process multiple promises at once to generate a new promise
// Promise.all(p1,p2)
let promise1 = new Promise(function(resolve,reject){
// resolve('promise11')
reject('promise11')})let promise2 = new Promise(function(resolve){
resolve('promise22')})Promise.all([promise1,promise2]).then(function(res){
console.log(res);
}).catch((res) = >{console.log(res);
})
Copy the code