Promise is used to asynchronous computations.
"Synchronize asynchronous methods" is always a hot topic.Here, "Promise" is one way to achieve the goal.
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"
})
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 => {
})
Promise.resolve() Promise.reject()
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.
Thanks for your reading. Welcome to subscribe my blog by Github.