The concept of "Promise"
Promise is used to asynchronous computations.
Introduction
"Synchronize asynchronous methods" is always a hot topic.Here, "Promise" is one way to achieve the goal.
Promise Model
Basic Promise Model
In javascript, it's like:
// #1 Create a "Promise" object
const testPromise = new Promise( (resolve, reject) => {
// resolve("parameters") or reject("parameters")
// example 1: setTimeout(resolve, 1000, 'parameters')
// example 2: setTimeout(reject, 1000, 'parameters')
} )
testPromise.then( value => {
// #2 Monitor the state of "Promise", if state is "fulfilled"
}, value => {
// #2 Monitor the state of "Promise", if state is "rejected"
})
Chaining promise model
const testPromise = new Promise( (resolve, reject) => {
// set the state of "Promise" to "fulfilled"
resolve()
} )
testPromise
.then( value => {
// Continue to create "Promise"
return new Promise( (resolve, reject) => {
resolve()
} )
}, value => {
})
.then( value => {
// Continue to create "Promise"
return new Promise( (resolve, reject) => {
resolve('parameters')
} )
}, value => {
})
.then( value => {
console.log(value) // output: 'paramaters'
}, value => {
})
Grammar
Initialize
Chain
Catch rejected reason
Resolve or reject parameters directly
Promise.resolve()
Promise.reject()
Queue
Apply fastest promise
Conclusion
There must be lots of ways to synchronize asynchronous methods, however, it's more convenient if a standard emerges so we can build robust program more easily.Obviously, promise is an ideal standard.