Home Web Front-end JS Tutorial Asynchronous processing analysis in JavaScript

Asynchronous processing analysis in JavaScript

Dec 04, 2017 am 11:32 AM
javascript js parse

Asynchronous processing is to handle problems according to asynchronous procedures. Asynchronous processing and synchronous processing are opposites, and what produces them is multi-threading or multi-process. The benefit of asynchronous processing is to increase device utilization, thereby improving program operation efficiency at a macro level, but the disadvantage is that conflicting operations and dirty data reading are prone to occur. In this article, we will share with you about asynchronous processing in JavaScript.

In the world of JavaScript, all code is executed in a single thread. Due to this "flaw", all network operations and browser events in JavaScript must be executed asynchronously. Asynchronous execution can be implemented using callback functions

Asynchronous operations will trigger a function call at a certain point in the future

The mainstream asynchronous processing solutions mainly include: callback function (CallBack), Promise, Generator Functions, async/await.

1. Callback function (CallBack)

This is the most basic method of asynchronous programming

Suppose we have a getData method, which is used to obtain data asynchronously. The first parameter is the URL address of the request, and the second parameter is the callback function, as follows:

function getData(url, callBack){    // 模拟发送网络请求
    setTimeout(()=> {        // 假设 res 就是返回的数据
        var res = {
            url: url,
            data: Math.random()
        }        // 执行回调,将数据作为参数传递
        callBack(res)
    }, 1000)
}
Copy after login

We set a scenario in advance, assuming that we want to request the server three times, and each request depends on the result of the previous request, as follows:

getData('/page/1?param=123', (res1) => {    console.log(res1)
    getData(`/page/2?param=${res1.data}`, (res2) => {        console.log(res2)
        getData(`/page/3?param=${res2.data}`, (res3) => {            console.log(res3)
        })
    })
})
Copy after login

As can be seen from the above code, the url address of the first request is: /page/1?param=123, and the returned result is res1.

The url address of the second request is: /page/2?param=${res1.data}, which depends on the res1.data of the first request, and the returned result is res2`.

The url address of the third request is: /page/3?param=${res2.data}, which depends on the res2.data of the second request, and the returned result is res3.

Since subsequent requests depend on the result of the previous request, we can only write the next request inside the callback function of the previous request, thus forming what is often said: callback hell.

2. Publish/Subscribe

We assume that there is a "signal center". When a certain task is completed, a signal is "published" to the signal center, and other tasks can be sent to the signal center. The signal center "subscribes" to this signal so that it knows when it can start execution. This is called the "publish-subscribe pattern" (publish-subscribe pattern), also known as the "observer pattern" (observer pattern)

There are many implementations of this pattern. The following is Ben Alman's Tiny Pub/ Sub, this is a plug-in for jQuery

First, f2 subscribes to the "Signal Center" jQuery "done" signal

jQuery.subscribe("done", f2);
Copy after login
f1进行如下改写
function f1(){                setTimeout(function(){                        // f1的任务代码                        jQuery.publish("done");                }, 1000);}
jQuery.publish("done") 的意思是, f1 执行完成后,向”信号中心 "jQuery 发布 "done" 信号,从而引发f2的执行。 此外,f2完成执行后,也可以取消订阅( unsubscribe )
jQuery.unsubscribe("done", f2);
Copy after login

The nature of this method is similar to "Event Listening", but it is obviously better to the latter. Because we can monitor the operation of the program by looking at the "Message Center" to see how many signals exist and how many subscribers each signal has.

3. Promise

Promise is a solution for asynchronous programming, which is more reasonable and powerful than traditional solutions - callback functions and events.

So-called Promise, simply put, is a container that stores the result of an event (usually an asynchronous operation) that will end in the future. Syntactically speaking, Promise is an object from which messages for asynchronous operations can be obtained. Promise provides a unified API, and various asynchronous operations can be processed in the same way

Simply put, the idea is that each asynchronous task returns a Promise object, which has a then method that allows specifying Callback.

Now we use Promise to re-implement the above case. First, we need to encapsulate the method of asynchronously requesting data into Promise

function getDataAsync(url){    return new Promise((resolve, reject) => {
        setTimeout(()=> {            var res = {
                url: url,
                data: Math.random()
            }
            resolve(res)
        }, 1000)
    })
}
Copy after login
Copy after login
Copy after login

Then the request code should be written like this

getDataAsync('/page/1?param=123')
    .then(res1=> {        console.log(res1)        return getDataAsync(`/page/2?param=${res1.data}`)
    })
    .then(res2=> {        console.log(res2)        return getDataAsync(`/page/3?param=${res2.data}`)
    })
    .then(res3=> {        console.log(res3)
    })
Copy after login

The then method returns a new Promise object. The chained calling of the then method avoids CallBack hell

But it is not perfect. For example, if we need to add a lot of then statements, we still need to write a callback for each then.

If the scenario is more complicated, for example, each subsequent request depends on the results of all previous requests, not just the results of the previous request, it will be more complicated. In order to do better, async/await came into being. Let's see how to use async/await to achieve

4. async/await

getDataAsync method remains unchanged, as follows

function getDataAsync(url){    return new Promise((resolve, reject) => {
        setTimeout(()=> {            var res = {
                url: url,
                data: Math.random()
            }
            resolve(res)
        }, 1000)
    })
}
Copy after login
Copy after login
Copy after login

The business code is as follows

async function getData(){ var res1 = await getDataAsync('/page/1?param=123') console.log(res1) var res2 = await getDataAsync(` /page/2?param=${res1.data}`) console.log(res2) var res3 = await getDataAsync(`/page/2?param=${res2.data}`) console.log(res3)
}

You can see that using async\await is just like writing synchronous code

How do you feel about comparing Promise? Is it very clear, but async/await is based on Promise, because the method decorated with async ultimately returns a Promise. In fact, async/await can be seen as using the Generator function to handle asynchronous syntactic sugar. Let’s take a look at how to use it. Generator function handles asynchronous

5. Generator

First of all, the asynchronous function is still

function getDataAsync(url){    return new Promise((resolve, reject) => {
        setTimeout(()=> {            var res = {
                url: url,
                data: Math.random()
            }
            resolve(res)
        }, 1000)
    })
}
Copy after login
Copy after login
Copy after login

Using the Generator function can be written like this

function*getData(){    var res1 = yield getDataAsync('/page/1?param=123')   
 console.log(res1)    var res2 = yield getDataAsync(`/page/2?param=${res1.data}`)   
  console.log(res2)    var res3 = yield getDataAsync(`/page/2?param=${res2.data}`)    console.log(res3))
}
Copy after login

Then we execute it step by step

var g = getData()
g.next().value.then(res1=> {
    g.next(res1).value.then(res2=> {
        g.next(res2).value.then(()=> {
            g.next()
        })
    })
})
Copy after login

上面的代码,我们逐步调用遍历器的 next() 方法,由于每一个 next() 方法返回值的 value 属性为一个 Promise 对象

所以我们为其添加 then 方法, 在 then 方法里面接着运行 next 方法挪移遍历器指针,直到 Generator 函数运行完成,实际上,这个过程我们不必手动完成,可以封装成一个简单的执行器

function run(gen){    var g = gen()    function next(data){        var res = g.next(data)        if (res.done) return res.value
        res.value.then((data) => {
            next(data)
        })
    }
    next()
}
Copy after login

run 方法用来自动运行异步的 Generator 函数,其实就是一个递归的过程调用的过程。这样我们就不必手动执行 Generator 函数了。 有了 run 方法,我们只需要这样运行 getData 方法

run(getData)

这样,我们就可以把异步操作封装到 Generator 函数内部,使用 run 方法作为 Generator 函数的自执行器,来处理异步。其实我们不难发现, async/await 方法相比于 Generator 处理异步的方式,有很多相似的地方,只不过 async/await 在语义化方面更加明显,同时 async/await 不需要我们手写执行器,其内部已经帮我们封装好了,这就是为什么说 async/await 是 Generator 函数处理异步的语法糖了

以上内容就是关于JavaScript中的异步处理,希望能帮助到大家。

相关推荐:

PHP异步处理的实现方案

详谈 Jquery Ajax异步处理Json数据

php 异步处理

The above is the detailed content of Asynchronous processing analysis in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
iBatis and MyBatis: Comparison and Advantage Analysis iBatis and MyBatis: Comparison and Advantage Analysis Feb 18, 2024 pm 01:53 PM

iBatis and MyBatis: Differences and Advantages Analysis Introduction: In Java development, persistence is a common requirement, and iBatis and MyBatis are two widely used persistence frameworks. While they have many similarities, there are also some key differences and advantages. This article will provide readers with a more comprehensive understanding through a detailed analysis of the features, usage, and sample code of these two frameworks. 1. iBatis features: iBatis is an older persistence framework that uses SQL mapping files.

A deep dive into the meaning and usage of HTTP status code 460 A deep dive into the meaning and usage of HTTP status code 460 Feb 18, 2024 pm 08:29 PM

In-depth analysis of the role and application scenarios of HTTP status code 460 HTTP status code is a very important part of web development and is used to indicate the communication status between the client and the server. Among them, HTTP status code 460 is a relatively special status code. This article will deeply analyze its role and application scenarios. Definition of HTTP status code 460 The specific definition of HTTP status code 460 is "ClientClosedRequest", which means that the client closes the request. This status code is mainly used to indicate

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Detailed explanation of Oracle error 3114: How to solve it quickly Detailed explanation of Oracle error 3114: How to solve it quickly Mar 08, 2024 pm 02:42 PM

Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

Parsing Wormhole NTT: an open framework for any Token Parsing Wormhole NTT: an open framework for any Token Mar 05, 2024 pm 12:46 PM

Wormhole is a leader in blockchain interoperability, focused on creating resilient, future-proof decentralized systems that prioritize ownership, control, and permissionless innovation. The foundation of this vision is a commitment to technical expertise, ethical principles, and community alignment to redefine the interoperability landscape with simplicity, clarity, and a broad suite of multi-chain solutions. With the rise of zero-knowledge proofs, scaling solutions, and feature-rich token standards, blockchains are becoming more powerful and interoperability is becoming increasingly important. In this innovative application environment, novel governance systems and practical capabilities bring unprecedented opportunities to assets across the network. Protocol builders are now grappling with how to operate in this emerging multi-chain

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Apache2 cannot correctly parse PHP files Apache2 cannot correctly parse PHP files Mar 08, 2024 am 11:09 AM

Due to space limitations, the following is a brief article: Apache2 is a commonly used web server software, and PHP is a widely used server-side scripting language. In the process of building a website, sometimes you encounter the problem that Apache2 cannot correctly parse the PHP file, causing the PHP code to fail to execute. This problem is usually caused by Apache2 not configuring the PHP module correctly, or the PHP module being incompatible with the version of Apache2. There are generally two ways to solve this problem, one is

See all articles