Get the App
SLTechnology News&Howtos  ›  Development  › 

How to execute Promise sequentially

Shulou Source: shulou.com Published: 2022-06-03 11:02:01 09月17日 Update

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!

Tags: Order result error method article output content processing verbosity not so much task most more knowledge industry information information channel channel chain reference Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Information Apple NVidia Docker