Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Promise.race () and Promise.any ()

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use Promise.race () and Promise.any (), has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

What is Promise?

Definition of Promise on MDN: the Promise object is used to represent the final completion (or failure) of an asynchronous operation and its resulting value. This may sound a little too complicated for beginners.

A big foreign man explained Promises as follows: "imagine you are a child. Your mother assures you that she will buy you a new mobile phone next week."

You won't know if you can get that phone until next week. Your mother either really bought you a brand new mobile phone, or she didn't buy it for you because she was unhappy.

This is a Promise. A Promise has three states. They are:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Pending: you don't know if you can get that phone.

Fulfilled: mom is happy and bought it for you.

Rejected: I'm done with Kansen. I won't buy it for you.

This is what I have heard so far, and I can understand Promise as soon as possible.

If you haven't started learning Promise yet, it is recommended that you do so.

Promise contains several very useful built-in methods. Today we will mainly introduce these two methods.

Promise.race ()-released with ES6

Promise.any ()-proposal that is still in stage 4

Promise.race ()

The Promise.race () method was originally released when Promise was introduced into ES6, and this method requires an iterable as a parameter.

The Promise.race (iterable) method returns a promise, and once a promise in the iterator is resolved or rejected, the returned promise is resolved or rejected.

Unlike the Promise.any () method, the Promise.race () method focuses on whether the Promise has been resolved, regardless of whether it is resolved or rejected.

Grammar

Promise.race (iterable)

Parameters.

Iterable-iterable object, similar to Array. The iterable object implements the Symbol.iterator method.

Return value

As long as a promise in a given iteration resolves or rejects a pending Promise, it takes the value of the first promise as its value, thus parsing or rejecting asynchronously (once the stack is empty).

Be careful

Because the parameters accept iterable, we can pass some values, such as basic values, or even objects in the array. In this case, the race method returns the first non-promise object passed. This is mainly because the behavior of the method is to return the value as soon as the value is available (when the promise is satisfied).

In addition, if a resolved Promise is passed in the iterable, the Promise.race () method resolves to the first of that value. If an empty Iterable is passed, the race method will always be in a pending state.

Case study

Const promise1 = new Promise ((resolve, reject) = > {setTimeout (resolve, 500, 'promise1 resolved');}); const promise2 = new Promise ((resolve, reject) = > {setTimeout (reject, 100,' promise2 rejected');}); const promise3 = new Promise ((resolve, reject) = > {setTimeout (resolve, 200, 'promise3 resolved')}); (async () = > {try {let result = await Promise.race ([promise1, promise2, promise3]) Console.log (result);} catch (err) {console.error (err);}}) (); / / output-"promise2 rejected" / / although promise1 and promise3 can be resolved, promise2 rejects faster than them. / / so the Promise.race method will be rejected as promise2

Real use case

Now, you may wonder, when do we Promise.race () in actual combat? Come see.

Display the load animation when data is requested

It is very common to use loading animation in development. When the data response time is long, if the load animation is not used, it looks as if there is no response. But sometimes, the response is so fast that we add a very small delay when we need to load the animation, which makes the user feel like I'm asking for it all the time. To do this, simply use the Promise.race () method, as shown below.

Function getUserInfo (user) {return new Promise ((resolve, reject) = > {/ / had it at 1500 to be more true-to-life, but 900is better for testing setTimeout (() = > resolve ("user data!"), Math.floor (900*Math.random ());});} function showUserInfo (user) {return getUserInfo (). Then (info = > {console.log ("user info:", info); return true;}) } function showSpinner () {console.log ("please wait...")} function timeout (delay, result) {return new Promise (resolve = > {setTimeout () = > resolve (result), delay);} Promise.race ([showUserInfo (), timeout (300)]) .then (displayed = > {if (! displayed) showSpinner ();})

* * cancelled Promise * *

In some cases, we need to cancel Promise, and we can also use the Promise.race () method:

Function timeout (delay) {let cancel; const wait = new Promise (resolve = > {const timer = setTimeout (() = > resolve (false), delay); cancel = () = > {clearTimeout (timer); resolve (true);};}); wait.cancel = cancel; return wait;} function doWork () {const workFactor = Math.floor (600*Math.random ()); const work = timeout (workFactor) Const result = work.then (canceled = > {if (canceled) console.log ('Work canceled'); else console.log (' Work done in', workFactor, 'ms'); return! canceled;}); result.cancel = work.cancel; return result;} function attemptWork () {const work = doWork () Return Promise.race ([work, timeout (300)]. Then (done = > {if (! done) work.cancel (); return (done? 'Work completes':'I gave up');});} attemptWork () .then (console.log)

Batch requests for long execution

Chris Jensen has an interesting use case for the race () method. He used the Promise.race () method to batch long-running requests. In this way, they can keep the number of parallel requests fixed.

Const _ = require ('lodash') async function batchRequests (options) {let query = {offset: 0, limit: options.limit}; do {batch = await model.findAll (query); query.offset + = options.limit If (batch.length) {const promise = doLongRequestForBatch (batch). Then () = > {/ / Once complete, pop this promise from our array / / so that we know we can add another batch in its place _ .remove (promises, p = > p = promise);}); promises.push (promise) / / Once we hit our concurrency limit, wait for at least one promise to / / resolve before continuing to batch off requests if (promises.length > = options.concurrentBatches) {await Promise.race (promises);} while (batch.length); / / Wait for remaining batches to finish return Promise.all (promises) } batchRequests ({limit: 100, concurrentBatches: 5})

Promise.any ()

Promise.any () receives an Promise iterable object and returns the promise that has succeeded as long as one of the promise succeeds. If none of the promise in the iterable object succeeds (that is, all promises fail / reject), an instance of the failed promise and AggregateError types is returned, which is a subclass of Error and is used to group single errors together. In essence, this method is the opposite of Promise.all ().

Note that the Promise.any () method is still experimental and has not been fully supported by all browsers. It is currently in the fourth phase of TC39 draft (Stage 4)

Grammar

Promise.any (iterable)

Parameters.

Iterable-an object that can be iterated, such as Array.

Return value

If the parameter passed in is an empty iterable object, a Promise with a failed (already rejected) state is returned.

If the passed parameter does not contain any promise, a * * asynchronous completion (asynchronously resolved) * * Promise is returned.

In other cases, a pending Promise is returned. As long as any promise in the incoming iteration object becomes a resolve state, or all of its promises fails, the returned promise becomes a success / failure state asynchronously (when the call stack is empty).

Description

This method is used to return the first successful promise. As long as one promise succeeds, this method terminates, and it does not wait for the other promise to complete.

Unlike Promise.all (), which returns a set of completion values (resolved values), we can only get one success value (assuming at least one promise is complete). This approach is useful when we only need one promise to succeed, not which one.

Also, unlike Promise.race (), which always returns the first result value (resolved/reject), this method returns the first successful value. This method will ignore all rejected promise until the first promise succeeds.

Case study

Const promise1 = new Promise ((resolve, reject) = > {setTimeout (reject, 100,' promise1 rejected');}); const promise2 = new Promise ((resolve, reject) = > {setTimeout (resolve, 400,' promise2 resolved at 400ms');}); const promise3 = new Promise ((resolve, reject) = > {setTimeout (resolve, 700,' promise3 resolved at 800ms');}) (async () = > {try {let value = await Promise.any ([promise1, promise2, promise3]); console.log (value);} catch (error) {console.log (error);}}) (); / / Output-"promise2 resolved at 400 ms"

Notice from the above code that Promise.any () is mainly concerned with parsing values. It ignores promise1 rejected at 100ms and takes into account the value of promise2 parsed after 400ms.

Real use case

Retrieve resources from the fastest server

Suppose that the users who visit our website may come from all over the world. If our server is based on a single location, the response time will vary depending on the location of each user. But if we have multiple servers, we can use the server that produces the fastest response. In this case, you can use the Promise.any () method to receive the response from the fastest server.

Thank you for reading this article carefully. I hope the article "how to use Promise.race () and Promise.any ()" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report