SoFunction
Updated on 2025-03-01

3 solutions to obtain JS asynchronous execution results

Preface

The JS asynchronous execution mechanism plays a very important role, especially in callback functions and events.

But asynchronous is sometimes very convenient, and sometimes it is very annoying. Let’s summarize the methods of obtaining asynchronous execution results.

Callback

This is the most traditional method and the simplest, as shown below

function foo(cb) {
 setTimeout(function() {
 cb(1); // Return the result through the parameters }, 2000);
}

foo(function(result) { // When calling the foo method, the data returned by the method is retrieved through the callback (result);
})

Promise

Promise is a new object added to ES6. It can encapsulate an asynchronous execution method into a method that supports synchronous operation. Combined with async/await, let's talk about how it encapsulates a method.

function foo() {
 return new Promise((resolve, reject) => {
 setTimeout(function() {
  resolve(1); // Return the successful result through the resolve parameter  // reject('error'); // Return the error message through reject parameter }, 2000);
 })
}

// Callfoo()
 .then(result => (result))
 .catch(error => (error));

From the above example, we can see that Promise uses the .then() function to get value, and exception handling uses the .catch() function to get exceptions

rxjs

rxjs is a design concept implementation framework of javascript language. The original name of rx is: ReactiveX

Official website is /

Open Source Address /ReactiveX/rxjs

The rx slogan is that everything is a stream, which is quite similar to the objects in Java. Its API is also all about streaming operations, and it is still very pleasant to write. Let's take a look at how to encapsulate a asynchronous operation by rxjs

Note that if you use this product, you must first install it in your own project, and then introduce dependencies. If it is a browser environment, you can introduce js.

import { Observable } from 'rxjs';

function foo() {
 return new Observable((observe) => {
 setTimeout(function() {
  (1); // Return the successful result through the () method  // ('error'); // Return the error message through the method }, 2000);
 })
}

// Callfoo()
 .subscribe(
 result => (result),
 error => (error)
 );

You can see that it is very similar to Promise, which has changed several parameter names, but it is much more powerful than Promise.

Let’s talk about the cancel operation in rxjs. Yes, the request can be cancelled. Only rxjs can implement this operation

import { Observable } from 'rxjs';

function foo() {
 return new Observable((observe) => {
 setTimeout(function() {
  (1); // Return the successful result through the () method  // ('error'); // Return the error message through the method }, 2000);
 })
}

// Call, return data after 2 seconds in the methodconst o = foo().subscribe(
 result => (result),
 error => (error)
);

// Set a timer for 1s and unsubscribe, so that the result will not be printed in the console, and the request will be cancelledsetTimeout(function() {
 (); // Unsubscribe}, 1000);

In addition to canceling execution, rxjs also has a function, loop execution, and can always receive the results returned by a request. You will understand by looking at the following example.

import { Observable } from 'rxjs';

function foo() {
 return new Observable((observe) => {
 let count = 0;
 setInterval(function() {
  (count++); // Return the successful result through the () method  // ('error'); // Return the error message through the method }, 1000);
 })
}

// Callfoo().subscribe(
 result => (result), // This line will print a data every 1s error => (error)
);

Because everything is a stream in ReactiveX, there are many convection operations APIs, such as fliter, map, etc., similar to stream operations in Java8. Let's take a look at the example below to illustrate it.

import { Observable } from 'rxjs';
// Convection operations need to be introduced into operation classesimport { map, filter } from 'rxjs/operators';

function foo() {
 return new Observable((observe) => {
 let count = 0;
 setInterval(function() {
  (count++); // Return the successful result through the () method  // ('error'); // Return the error message through the method }, 1000);
 })
}

// Callconst o = foo();
(
 filter((value: number) => value % 2 === 0),
 map((value: number) => value *= 2)
).subscribe(data => (data));

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.