What is Promise?
The Promise object is a constructor.
Accept a function as an argument, resolve,reject.
The state of the Promise object is never completed to success. Upon success, the result of the asynchronous operation is passed as a parameter.
Reject The state of the Promise object never completes until it fails. When it fails, the result of the asynchronous operation is passed as a parameter.
The then() method specifies the resolve and reject callbacks, respectively.
The catch() method returns a Promise and handles the rejection. It behaves the same as calling promise.prototype. then(undefined, onRejected).
Use the catch method instead of defining the rejected state callback in the THEN method. This is because using catch can also catch errors in the execution of the THEN method.
var p = new Promise(function(resolve,reject){
if(true){
resolve('ok')}else {
reject('error')
}
})
p.then(function(v){
console.log(v) // ok
},fuction(v){
console.log(v) // error
})
Copy the code
Parallel writing
all
let p1 = new Promise(function(resolve,reject){
setTimeout(() => {
resolve('ok')}, 500)})let p2 = new Promise(function(resolve,reject){
setTimeout(() => {
resolve('error')
},1000)
})
Promise.all([p1,p2]).then(([v1,v2]) => {
console.log(v1)
console.log(v2)
},(err) => {
console.log(err)
})
Copy the code
Race returns results fast, and whoever returns fast returns who. Success or failure
Promise to encapsulate the ajax
const getJson = function (url, type, data) {
const promise = new Promise(function (resolve, reject) {
const handler = function () {
if(this.readyState ! = = 4) {return;
}
if (this.status == 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
const client = new XMLHttpRequest();
client.open(type, url);
client.onreadystatechange = handler;
client.responseType = 'json';
if (type= ='get') {
client.send(data);
} else {
client.setRequestHeader("Content-Type"."application/json"); client.send(JSON.stringify(data)); }}); }Copy the code
Jquery (Ajax) uses then, jQ version greater than 1.5
$({url: '/get/data'.type:'get',dataType:'json'}).then(res => {
console.log(res)
},(err) => {
console.log(err)
})
Copy the code
$({url: '/get/data'.type:'get',dataType:'json'}).done(res => { //thenThe method has a return value, which is passed to the next chaindoneConsole. log(res)})fail((err) => {console.log(err)})Copy the code
Jq uses the WHEN method in parallel
$.when($({url: '/get/data'.type:'get',dataType:'json'}),$({url: '/get/data1'.type:'get',dataType:'json'})).then((v1,v2) => {
console.log(v1)
console.log(v2)
},(err) => {
console.log(err)
})
Copy the code
async
// async is a keyword in front of a function, indicating that the function is an asynchronous function asyncfunction test(){// Async returns an instance of Promise by default, a state of success by default, and passes the return value of the function tothenThe first argument toreturn 'hello world'
}
test(a); console.log('123456') // Enter 123456,test() returns a PromiseCopy the code
async function test() {return 'hello world'
}
test().then(res => {
console.log(res)
})
console.log('123456'// Output 123456 Hello worldCopy the code
await
Wait for asynchronous synchronization
function f(){
console.log('f')
}
console.log('1')
async function test() {
console.log('2') await f(); // the code under await will wait until asynchronous execution is complete in the function before executing console.log()'3')}test(a)Copy the code