Detailed explanation of the initial use of Promise in JavaScript asynchronous programming

Detailed explanation of the initial use of Promise in JavaScript asynchronous programming

1. Overview

The Promise object is a specification for asynchronous programming proposed by ES6. When it comes to asynchronous programming, we have to talk about the concepts of synchronization and asynchrony.

If we understand synchronous programming literally, it seems to mean that two tasks run synchronously. This is a wrong understanding (at least I had this misunderstanding before I came into contact with this concept). Synchronous and asynchronous refer to the order in which the code specifies execution (the execution order of the structured programming paradigm is always from top to bottom and from front to back). If the execution order is the same as the code, it is synchronous; if it is different, it is asynchronous.

Initially, operating systems were command-line based, and all languages ​​were designed with synchronous statements. In this case, there was no need for asynchronous programming. But soon, the graphical operating interface came out, and all programming languages ​​had to deal with GUI. What we must understand is that a GUI program is an interface program that is constantly drawing:

while(done)
{
    dosomething();
    drawGUI();
}

If the event of the task dosomething() executed in each loop is too long, the interface will not receive drawing commands for a long time, and the intuitive manifestation is lag. To solve this problem, browsers that use JavaScript as scripts generally adopt the event loop mechanism:

  • Time-consuming behaviors are defined as events, and events are bound to response callback functions.
  • Each loop, prioritize synchronous code.
  • The synchronous code is completed, and the events are traversed in the order in which they are executed.
  • In the remaining loop without synchronization code, the corresponding functions of the events are executed in sequence.

In this way, in the case of single thread, the execution order of tasks is modified and an asynchronous mechanism is implemented. Because the synchronization behavior is always completed quickly and the interface is drawn in time, the interface lag phenomenon is greatly improved.

The event loop mechanism defines the input and output of UI devices as events. In fact, there are many time-consuming behaviors, but they are generally related to IO. For IO-related behaviors, JavaScript provides asynchronous behavior codes. For example, here is an example of loading a picture.

2. Detailed discussion

First, prepare an HTML page PromiseTest.html and load the JS script PromiseTest.js in this HTML page:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="./3rdParty/jquery-3.5.1.js"></script>
    <title>Sample</title>
</head>

<body>
    <div id = "container"> </div>
    <script src="./PromiseTest.js"></script>
</body>

</html>

The native JS image object Image implements asynchronous loading of images through events:

$(function () {    
    var img = new Image();
    img.onload = function () { 
        $(img).appendTo($('#container'));        
    };
    img.src = "./img.jpg";    
});

Add a corresponding function to the onload event handler of Image. When the image is loaded, add the loaded Image to a div element child node of the HTML page. Open this page through the browser and the picture of the corresponding address will be displayed directly.

Of course, this JS script can also be rewritten through Promise:

$(function () {    
    function getImg(uri){
        return new Promise(function(resolve, reject){
            var img = new Image();
            img.onload = function () {
                resolve(img);
            };
            img.onerror = function () {
                reject(Error("Load Image Error!"));
            }
            img.src = uri;
        });   
    }  
    
    var imgUri = "./img.jpg";
    getImg(imgUri).then(function(img){
        $(img).appendTo($('#container')); 
    }, function(error){
        console.error("Failed!", error);
    })
});

At first glance, using Promise seems to make the program more complicated and cumbersome. But we need to deeply understand the connotation of the Promise mechanism. This design is not for fun.

  • A Promise object represents an action that is scheduled to be performed but has not yet started. Since it is an action, of course it must be planned and the results of the action must be specified: if it succeeds, execute resolve; if it fails, execute reject. Generally we can define a function and return a Promise object.
  • Call the function that returns the Promise object, so that the desired behavior is actually started. However, resolve and reject are just two callback functions, so the then method is used to specify the actual processing functions corresponding to success and failure.

As you can see, this design looks complicated, but it is very much like a synchronous behavior: specify an unfinished behavior object, how to handle it when the behavior is completed, and how to handle it when the behavior fails. And this is also the purpose of Promise: to make asynchronous operations more like synchronous behavior.

3. References

Synchronous and Asynchronous

Briefly describe the principle of JS single-threaded asynchronous implementation

Detailed explanation of JavaScript operation mechanism: Let’s talk about Event Loop again

This is the end of this article about the initial use of Promise in JavaScript asynchronous programming. For more relevant content on the use of js Promise, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript uses promise to handle multiple repeated requests
  • Example analysis of the usage of node.js Promise object
  • Detailed explanation of using Promise in WeChat applet JS script to optimize function processing
  • js uses Promise to implement simple Ajax caching
  • Using Promise in JS to implement traffic light example code (demo)
  • Detailed explanation of the use of Promise in JavaScript
  • Detailed explanation of Promise usage in javascript

<<:  Detailed explanation of the standard MySQL (x64) Windows version installation process

>>:  Summary of Docker Data Storage

Recommend

Linux uses suid vim.basic file to achieve privilege escalation

Reproduce on Kali First set suid permissions for ...

3 different ways to clear the option options in the select tag

Method 1 Copy code The code is as follows: documen...

CSS imitates Apple's smooth switch button effect

Table of contents 1. Code analysis 2. Source code...

JavaScript BOM location object + navigator object + history object

Table of contents 1. Location Object 1. URL 2. Pr...

Three ways to draw a heart shape with CSS

Below, we introduce three ways to draw heart shap...

Solution to the Docker container being unable to access the host port

I recently encountered a problem at work. The doc...

Detailed explanation of the correct way to install opencv on ubuntu

This article describes how to install opencv with...

mysql5.7.14 decompressed version installation graphic tutorial

MySQL is divided into Community Edition (Communit...

50 Super Handy Tools for Web Designers

Being a web designer is not easy. Not only do you...

JavaScript function call, apply and bind method case study

Summarize 1. Similarities Both can change the int...

Linux system to view CPU, machine model, memory and other information

During system maintenance, you may need to check ...

Analysis of several situations where MySQL index fails

1. Best left prefix principle - If multiple colum...