Please help me fix the sequence of node js (java script) functions

Asked 1 years ago, Updated 1 years ago, 76 views

Hello, I'm a beginner developer who's making a server for the first time. You are about to run a function to create a server.

func a();
func b();
func c();
func d();
func last();

I want to order these five functions, and I want the last() function to be executed at the end of a()b(), c()d() and last().
a -> b -> c -> d -> last, I don't think you can take advantage of node js asynchronous if you set all the order synchronously.
(a, b, c, d) -> last I want to order it in this way. Regardless of the order in parentheses, I want to operate asynchronously!
Is there a good way?

In addition, functions such as a, b, c, d, etc. are functions that import data from the database The last function is a function that executes rendering based on the imported data.

node.js javascript asynchronous sync

2022-09-21 20:51

1 Answers

First, a,b,c,d must all return a promise.

Usually, you will use a library of connectors (called adapters, drivers, etc.) imported from DB. Make sure that the asynchronous function return value of the library is promise.

If the return value is not a prompt, create a function that wraps to return a prompt.

After that,

Promise
    .all([a(), b(), c(), d()])
    .then(() => last())

// Or
(async () => {
    await Promise.all([a(), b(), c(), d()]);
    last();
})();

However, you should pay attention to handling exceptions in the code above. It is recommended that you design and use it in advance so that you can check which of a,b,c,d errors occurred in .catch() or try catch.


2022-09-21 20:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.