Learn about JavaScript Promise

Tram Ho

One of the things that you have to get used to when switching to Javascript is that asynchronous (Asynchronous) is different from the concept of synchronous (Synchronous) that we are familiar with in languages ​​like C # .NET or PHP.

1. Callback and Callback hell

Asynchronous programming, we still use a mechanism called callback:

The setTimeout function aims to simulate the environment like you get data from a certain url. What will be printed out in the browser console will be:

Asynchronous here means that the browser will not wait until it gets data to run the next command ( console.log('b') ) but will keep running and the data will print at any time. there. Print out hello wolrd! can be a few minutes from the printout b, depending on the parameters we enter. The question is that the callback has already solved the asynchronous problem, why it is necessary to generate Promise. Promise is basically an asynchronous programming technique but has advantages over callback, typically as follows:

This is called callback hell, when the http requests depend on each other, the sense of the endless repeated function is difficult to follow. Luckily, Promise helps us to solve this problem.

2. Promise and Promise chaining

Basically Promise carries its literal meaning – a promise. It’s like the kind your mother promised when she was a child: if your kids are good, they will go to the park. A promise, as you know, can or may not be fulfilled depending on the person making the promise and other external conditions. It only describes what you will get if all conditions are fulfilled. Obedient for example, obedient, everything also has. Rewrite the above example with Promise as follows:

This time we take the example get content of a url to simulate more accurately because it has an error case, if it is setTimeout there will never be an error. In the above function, resolve is like her mother giving you a reward. If you forget to resolve, you won’t get anything like when she forgot, and you have to say so. Similar to reject, the thing passed to the reject function must be an instance of the error, otherwise you won’t be able to catch it later. Of course if you don’t call reject, you will never know if you have a reward. At this point, you may think “Nothing special”, but Promise has two convenient then and catch methods.

The then function has 2 parameters in the order of success handler and failure handler but usually people will not pass in the second parameter. Then the result is a Promise, so we can continue calling then from the object. returns – also known as Promise chaining as shown below. If for some reason you do not pass both parameters or 2 parameters that are not a function then a new Promise will be returned with the value of the previously called Promise.

The first then function has two non-function parameters so the Promise returned by the test () function will go through the first then function and to the second then without any changes. If the handlers (either success handler or failure handler ) return a value then the function will return a Promise with that value and the state is successful, if return or throw an error then the function will return a Promise with the value of error. and state is failure.

Results received will be successful with result hello.

then the received result is failed with error oops! .

The catch function takes an input parameter which is a failure handler so it only applies to errors. Calling catch is exactly the same as calling then with the first parameter undefined. The following two callings are completely equivalent:

If test() returns a Promise with a successful state then console.log(error) will never be called and the Promise return from test() will be returned for the next then or catch (if applicable).

Rewrite example 2 using Promise as follows:

It’s easier to see callback hell above, right? We can call then and catch interwoven to make it easy to see as follows:

It is also possible to not use catch at all, but it will seem incomprehensible with the above interlaced approach:

3. Switch from callback to Promise

With the old Browser, Promise does not support native, so we often have to use external libraries like async or q. I will show you how to switch from callback to Promise using Mongoose library. For simplicity I take the classic example of todo and assume you already have the todo schema :

models / todo.js

repository / todoRepository.js

With Browser support Promise we don’t need to use external libraries anymore. todoRepository.js will revise a bit as follows:

In a nutshell Promise is so, very simple to understand, about other async libs will probably find the opportunity to share with everyone in another post.

Share the news now

Source : Viblo