How to execute Promise sequentially
Editor to share with you how to implement Promise in order, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
The result of Promise.all () is output sequentially, but the execution is parallel. To execute Promise sequentially, use his than method, but this is too long, how to use the all method to achieve sequential execution?
Promise.all executes promise in parallel
GetA and getB execute in parallel, and then output the results. If there is a mistake, throw it
/ * *
* each promise must return a resolve result to be correct
* each promise does not handle errors
* /
ConstgetA=newPromise ((resolve,reject) = > {
/ / simulate asynchronous tasks
SetTimeout (function () {
Resolve (2)
}, 1000)
})
.then (result= > result)
ConstgetB=newPromise ((resolve,reject) = > {
SetTimeout (function () {
/ / resolve (3)
Reject ('ErroringetB')
}, 1000)
})
.then (result= > result)
Promise.all ([getA,getB]) .then (data= > {
Console.log (data)
})
.catch (e = > console.log (e))
GetA and getB execute in parallel, and then output the results. Always return resolve result
/ * *
* each promise handles errors on its own
* /
Sequential execution of promise
First getA, then getB execution, finally addAB
Method 1-continuous use of then chain operation
FunctiongetA () {
ReturnnewPromise (function (resolve,reject) {
SetTimeout (function () {
Resolve (2)
}, 1000)
})
}
FunctiongetB () {
ReturnnewPromise (function (resolve,reject) {
SetTimeout (function () {
Resolve (3)
}, 1000)
})
}
The above is all the contents of the article "how to execute Promise in order". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!