1. The difference between asynchronous writing
ES5 is normally written
getAjax(url,(res)=>{})
Copy the code
Promise
get(url).then((res)=>{})
Copy the code
async_await
(async ()=>{
let res = await get(url)
})()
Copy the code
Conclusion:
- The main difference between ES5 and promise is the way we write it, we can divide the callback out to.then
In order to make the code more efficient, you can also write two different arguments separately
- The difference between async and promise lies in the syntactic sugar of promise in async, which is written at the bottom
When compiled, it automatically converts to promise.
2.Promise implementation principle
2.1 Functions that promise needs to implement
function fn(resolve,reject){
setTimeout(() = >{
if(true){
resolve()
}else{
reject()
}
})
}
var p1 = new myPromise(fn)
p1.then(function(res){
document.body.style.background = "greenyellow"
console.log("This is a successful thing to do.")
console.log(res)
})
p1.catch(function(res){
document.body.style.background = "pink"
console.log("This is what failure does.")
console.log(res)\
})
Copy the code
The P1Promise object sends an asynchronous operation, which is bound to happen1Future events to be performed in the future. This process is performed by the passed function object FN. Function fn necessarily requires a function executed on success and a function executed on failureCopy the code
2.2 Creating a class constructs an object
class myPromise{
constructor(fn) {
// Integrate successful event functions into the successList array
this.successList = [];
// All failed functions are integrated into failList
this.failList = []
//pending,fullfilled,rejected
this.state = "pending"
// The function object passed in,(the function content of the asynchronous operation)
fn(this.resolveFn.bind(this),this.rejectFn.bind(this))}}Copy the code
The constructor does:
Declares an array object placed by the success function
Declares an array object placed by the failed function
Define the initialization state
Call the incoming function that executes asynchronous content (the incoming success function is called in case of future success and the incoming failure function is called in case of future failure)
2.3 Passing in the function to be called on success or failure
class myPromise{
constructor(fn) {
// Integrate successful event functions into the successList array
this.successList = [];
// All failed functions are integrated into failList
this.failList = []
//pending,fullfilled,rejected
this.state = "pending"
// The function object passed in,(the function content of the asynchronous operation)
fn(this.resolveFn.bind(this),this.rejectFn.bind(this))}then(successFn,failFn){
if(typeof successFn=='function') {this.successList.push(successFn)
}
if(typeof failFn=='function') {this.failList.push(failFn)
}
}
catch(failFn){
if(typeof failFn=='function') {this.failList.push(failFn)
}
}
}
Copy the code
Function:
Pass the success and failure functions into the success and failure array
2.4 Define successful and failed functions
//promise aysnc await proxy Iteratror
class myPromise{
constructor(fn) {
// Integrate successful event functions into the successList array
this.successList = [];
// All failed functions are integrated into failList
this.failList = []
//pending,fullfilled,rejected
this.state = "pending"
// The function object passed in,(the function content of the asynchronous operation)
fn(this.resolveFn.bind(this),this.rejectFn.bind(this))}then(successFn,failFn){
if(typeof successFn=='function') {this.successList.push(successFn)
}
if(typeof failFn=='function') {this.failList.push(failFn)
}
}
catch(failFn){
if(typeof failFn=='function') {this.failList.push(failFn)
}
}
resolveFn(res){
this.state = "fullfilled"
this.successList.forEach(function(item,index){
// Call the successful event loop
item(res)
})
}
rejectFn(res){
this.state = 'rejected'
// Register to fail all events are called
this.failList.forEach(function(item,index){
item(res)
})
throw Error(res); }}Copy the code
Function:
Call all the functions in the success array on success, all the functions in the failure array on failure.
3. The application of
3.1 How do I combine promise with async and await
Callback operations for typical asynchronous reads and writes
fs.readFile(path,{fagg'r',encodingg"utf-8"},function(err,data){
if(err){
//console.log(err)
// Failed to execute
reject(err)
}else{
//console.log(data)
// Successful execution
resolve(data)
}
//console.log(456)
})
Copy the code
Convert to a Promise object
new Promise(function(resolve,reject){
fs.readFile(path,{fagg'r',encodingg"utf-8"},function(err,data){
if(err){
reject(err)
}else{
resolve(data)
}
})
})
Copy the code
Because I don’t want to write that much code every time I use it, I’m just going to wrap it up
function fsRead(path){
return new Promise(function(resolve,reject){
fs.readFile(path,{fagg'r',encodingg"utf-8"},function(err,data){
if(err){
reject(err)
}else{
resolve(data)
}
})
})
}
Copy the code
When you use it, you can write it as promise
p1 = fsRead(path) // Get the promise object
p1.then(function(data){
console.log('Output data g',data)
})
Copy the code
Asycn_await writing
(async() = > {let data = await fsRead(path)
})()
Copy the code
An asynchronous async function call is also followed by a Promise object
(async() = > {async function test(){
let data = await fsRead(path)
return data;
}
let p = test()// After an asynchronous function call, it is also a Promise object
p.then(function(data){
console.log(data)
})
let a = await test()// After an asynchronous function call, it is also a Promise object
console.log(123)
})()
Copy the code