1. Concept: Promise is a solution for asynchronous programming, which is more reasonable and powerful than the traditional solution - callback functions and events. Promise is simply a container containing the results of a future event (usually an asynchronous operation).
Generally speaking, Promise is a promise, a promise, a promise to the future. Promise may not be fulfilled, but whether it can be fulfilled or not, it will have a result.
Pending is doing...
Resolved Fulfilling this commitment
Rejected This promise has not been fulfilled and has failed.
Promise Used to schedule a task that may not necessarily be accomplished, either successful or unsuccessful
Specifically embodied in specific procedures, usually used to encapsulate an asynchronous task and provide promised results
Promise It is a solution of asynchronous programming, mainly used to solve the problem of callback hell, which can effectively reduce callback nesting.
2, characteristics:
(1) The state of the object is not affected by the outside world. Promise objects represent an asynchronous operation in three states: Pending (in progress), Resolved (completed, also known as Fulfilled) and Rejected (failed). Only the result of an asynchronous operation can determine which state it is currently, and no other operation can change that state.
(2) Once the state changes, it will not change again, and this result can be obtained at any time. There are only two possibilities for the state change of Promise objects: from Pending to Resolved and from Pending to Rejected. As long as these two situations occur, the state will be solidified, will not change any more, will always maintain this result. Even if the change has happened, you can immediately get the result by adding a callback function to the Promise object.
3, disadvantages:
(1) Promise cannot be cancelled. Once it is newly built, it will be executed immediately. It cannot be cancelled halfway. Unlike ordinary objects, there is no need to call them.
(2) If the callback function is not set, the errors thrown inside Promise will not be reflected outside.
(3) When in the Pending state, it is impossible to know which stage the current progress is going to be (just beginning or near completion).
4. Basic API(node server-side test promise.js)
const fs = require('fs')// Prom.js file
(1)new Promise
new Promise((resolve,reject)=>{ fs.readFile('./data/a.txt','utf8',(err,data)=>{ if(err){ reject(err) } resolve(data) }) })
(2)PromiseObj.then(resolveFn,rejectFn)
resolveFn: A successful callback handler for Promise objects, pointing to resolve
rejectFn: The callback handler for Promise object failure
new Promise((resolve,reject)=>{
fs.readFile('./data/a.txt','utf8',(err,data)=>{
if(err){
return reject(err)
}
resolve(data)
})
}).then((resolveData)=>{
console.log(resolveData) // Contents in the'. / data/a.txt'file
},(rejectErr)=>{
})
Fs. readFile ('. / data / A. txt','utf8', (err, data) => {if (err) {return reject (err)} resolve (data)})} then (data => {console. log (data) / /'. / A. txt'file content})/*Except for the first then, all the subsequent ones are returned from the previous then. then There are three situations when the result is received: 1. If the last one has no return value, it is undefined. 2. The last one has normal return values: arrays, numbers, strings, objects... 3. The last then returned a new Promise object If a Promise object is returned from the previous one, Then the callback handler for the then points to resolve in the Promise object returned from the last then*/ new Promise((resolve,reject)=>{ fs.readFile('./data/a.txt','utf8',(err,data)=>{ if(err){ return reject(err) } resolve(data) }) }).then((resolveData)=>{ console.log(resolveData) // Contents in the'. / data/a.txt'file },(rejectErr)=>{ }).then(data=>{ console.log(data) //undefined return [1,2,3] }).then(data=>{ console.log(data) //[1,2,3]return new Promise((resolve,reject)=>{
(3)Promise.all()
The Promise constructor has an all method, all method, which receives an array of Promise object instances stored in the parameter array, passes multiple Promise object instances as an array to Promise.all([p1, p2, p3]) and then passes the return value of Promise.all(): the new Promise object calls the then method of the new Promise object to get the result at the same time Promi object. Se.all The method waits for all asynchronous tasks to finish, then unifies the execution results of all tasks into an array, and passes them to its then.
function readFile(filePath, encoding) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, encoding, (err, data) => {
if (err) {
return reject(err)
}
resolve(data)
})
})
}
Promise
.all([readFile('./data/a.txt', 'utf8'), readFile('./data/b.txt', 'utf8'), readFile('./data/c.txt', 'utf8')])
.then(data => {
console.log(data) // ['a a a a','b B B B b','C c c c c c c c'], each element is'. / data / A. txt','. / data / b. txt','. / data / C. txt'
//Contents in three documents
})
.catch(err => {
console.log(err)
})
(4)PromiseObj.catch()
new Promise((resolve,reject)=>{
reject('Error')
})
.catch(err=>{
console.log(err) // Error
})
(5)PromiseObj.resolve()
Convert a value, number, string... to a Promise object
Promise.resolve(111)
.then(data=>{
console.log(data) //111
})
(6)PromiseObj.reject()
Promise.reject('Error')
.then(null,err=>{
console.log(err)//Error
})
// Equivalent to
new Promise((resolve,reject)=>{
reject('Error')
})
.then(null,err=>{
console.log(err) //Error
})