search
HomeWeb Front-endJS TutorialA detailed discussion of nodejs asynchronous programming_node.js

Current requirements involve a large number of asynchronous operations, and actual pages are increasingly leaning towards single-page applications. In the future, you may use backbone, angular, knockout and other frameworks, but the issue about asynchronous programming is the first issue that needs to be faced. With the rise of node, asynchronous programming has become a very hot topic. After a period of study and practice, some details of asynchronous programming are summarized.

1. Classification of asynchronous programming

Methods to solve asynchronous problems generally include: direct callback, pub/sub mode (event mode), asynchronous library control library (such as async, when), promise, Generator, etc.
1.1 Callback function

Callback function is a commonly used method to solve asynchronous problems. It is often contacted and used, easy to understand, and very easy to implement in libraries or functions. This is also a method often used by everyone when using asynchronous programming.

But the callback function method has the following problems:

1. It may form an evil nested pyramid, and the code is difficult to read;

2. Can only correspond to one callback function, which becomes a limitation in many scenarios.

1.2 pub/sub mode (event)

This mode is also called event mode, which is the eventization of callback functions. It is very common in libraries such as jQuery.

The event publishing subscriber model itself does not have the problem of synchronous and asynchronous calls, but in node, emit calls are mostly triggered asynchronously with the event loop. This mode is often used to decouple business logic. The event publisher does not need to pay attention to the registered callback functions, nor the number of callback functions. Data can be transferred flexibly through messages.

The advantages of this mode are: 1. Easy to understand; 2. No longer limited to one callback function.

Disadvantages: 1. Need to use class library; 2. The order of events and callback functions is very important

Copy code The code is as follows:

var img = document.querySelect(#id);
img.addEventListener('load', function() {
// Image loading completed
 …
});
img.addEventListener('error', function() {
// Something went wrong
……
});

There are two problems with the above code:

a. The img has actually been loaded, and the load callback function is bound only at this time. As a result, the callback will not be executed, but we still hope to execute the corresponding callback function.

Copy code The code is as follows:

var img = document.querySelect(#id);
function load() {
...
}
if(img.complete) {
load();
} else {
img.addEventListener('load', load);
}
img.addEventListener('error', function() {
// Something went wrong
……
});

b. Unable to handle exceptions well

Conclusion: The event mechanism is most suitable for handling things that happen repeatedly on the same object. There is no need to consider the occurrence of events before the callback function is bound.

1.3 Asynchronous control library

The current asynchronous libraries mainly include Q, when.js, win.js, RSVP.js, etc.

The characteristic of these libraries is that the code is linear and can be written from top to bottom, which is in line with natural habits.

The disadvantage is that the styles are different, which makes it difficult to read and increases the cost of learning.

1.4 Promise

Promise is translated into Chinese as promise. My personal understanding is that after the asynchronous completion, it will give an external result (success or failure) and promise that the result will not change. In other words, Promise reflects the eventual return value of an operation (A promise represents the eventual value returned from the single completion of an operation). At present, Promise has been introduced into the ES6 specification, and advanced browsers such as Chrome and Firefox have implemented this native method internally, which is very convenient to use.

Let’s analyze the characteristics of Promise from the following aspects:

1.4.1 Status

Contains three states: pending, fulfilled, and rejected. Only two transitions can occur among the three states (from pending--->fulfilled, pending-->rejected), and the state transition can only occur once.

1.4.2 then method

The then method is used to specify the callback function after the asynchronous event is completed.

This method can be said to be the soul method of Promise, which makes Promise full of magic. There are several specific manifestations as follows:

a) The then method returns Promise. This enables serial operations of multiple asynchronous operations.

Regarding the processing of value in the yellow circle 1 in the above picture, it is a more complicated part of Promise. The processing of value is divided into two situations: Promise object and non-Promise object.

When value is not of Promise type, just use value as the parameter value of the resolve of the second Promise; when it is of Promise type, the status and parameters of promise2 are completely determined by value. It can be considered that promsie2 is completely a puppet of value. , promise2 is just a bridge connecting different asynchronous ones.

Copy code The code is as follows:

Promise.prototype.then = function(onFulfilled, onRejected) {
    return new Promise(function(resolve, reject) {           //此处的Promise标注为promise2
        handle({
            onFulfilled: onFulfilled,
            onRejected: onRejected,
            resolve: resolve,
            reject: reject
        })
    });
}
function handle(deferred) {
    var handleFn;
    if(state === 'fulfilled') {
        handleFn = deferred.onFulfilled;
    } else if(state === 'rejected') {
        handleFn = deferred.onRejected;
    }
    var ret = handleFn(value);
    deferred.resolve(ret);                           //注意,此时的resolve是promise2的resolve
}
function  resolve(val) {
    if(val && typeof val.then === 'function') {
        val.then(resolve);                           // if val为promise对象或类promise对象时,promise2的状态完全由val决定
        return;
    }
    if(callback) {                                    // callback为指定的回调函数
        callback(val);
    }
}

  b)实现了多个不同异步库之间的转换。

    在异步中存在一个叫thenable的对象,就是指具有then方法的对象,只要一个对象对象具有then方法,就可以对其进行转换,例如:

复制代码 代码如下:

var deferred = $('aa.ajax');      // !!deferred.then  === true
var P = Promise.resolve(deferred);
p.then(......)

1.4.3 commonJS Promise/A规范

      目前关于Promise的规范存在Promise/A和Promise/A 规范,这说明关于Promise的实现是挺复杂的。

复制代码 代码如下:

then(fulfilledHandler, rejectedHandler, progressHandler)

1.4.4 注意事项

     一个Promise里面的回调函数是共享value的,在结果处理中value作为参数传递给相应的回调函数,如果value是对象,那就要小心不要轻易修改value的值。

复制代码 代码如下:

var p = Promise.resolve({x: 1});
p.then(function(val) {
    console.log('first callback: ' val.x );
});
p.then(function(val) {
    console.log('second callback: ' val.x)
})
// first callback: 1
// second callback: 2

1.5 Generator

All the above methods are based on callback functions to complete asynchronous operations. They are nothing more than encapsulation of callback functions. Generator is proposed in ES6, which adds a way to solve asynchronous operations and no longer relies on callback functions.

The biggest feature of Generator is that it can pause and restart functions. This feature is very helpful for solving asynchronous operations. Combining Generator's pause with promise's exception handling can solve asynchronous programming problems more elegantly. Specific implementation reference: Kyle Simpson

2. Problems with asynchronous programming

2.1 Exception handling

a) Asynchronous events include two links: issuing asynchronous requests and result processing. These two links are connected through event loop. Then when try catch is used to capture exceptions, it needs to be captured separately.

Copy code The code is as follows:

try {
asyncEvent(callback);
} catch(err) {
 …
}

The above code cannot capture the exception in the callback, but can only get the exception in the request process. This creates a problem: If the issuance of the request and the processing of the request are completed by two people, will there be a problem when handling exceptions?

b) Promise implements exception delivery, which brings some benefits and ensures that the code is not blocked in actual projects. But if there are many asynchronous events, it is not easy to find out which asynchronous event caused the exception.

Copy code The code is as follows:

// Scenario description: Display price alarm information in CRM, including competition information. However, it takes a long time to obtain the competition information. In order to avoid slow queries, the backend split a record into two pieces and obtained them separately.
// Step one: Get price alarm information, in addition to competition information
function getPriceAlarmData() {
Return new Promise(function(resolve) {
Y.io(url, {
Method: 'get',
               data: params,
on: function() {
Success: function(id, data) {
resolve(alarmData);
                }
            }
        });
});
}
// After getting the alarm information, get the competition information
getPriceAlarmData().then(function(data) {
//Data rendering, except for competition information
render(data);
Return new Promise(function(resolve) {
Y.io(url, {
Method: 'get',
              data: {alarmList: data},
on: function() {
Success: function(id, compData) {
                        resolve(compData);
                }
            }
        });
});
}) // After obtaining all the data, render the competition information
.then(function(data) {
// Render competition information
render(data)
}, function(err) {
//Exception handling
console.log(err);
});

You can convert the above code into the following:

Copy code The code is as follows:

try{
// Get alarm information other than competition
var alarmData = alarmDataExceptCompare();
render(alarmData);
// Query competition information based on alarm information
var compareData = getCompareInfo(alarmData);
render(compareData);
} catche(err) {
console.log(err.message);
}

In the above example, exception handling is placed at the end, so that when an exception occurs in a certain link, we cannot accurately know which event caused it.       

2.2 Problems with jQuery.Deferred

Asynchronous operations are also implemented in jQuery, but the implementation does not comply with the promise/A specification, mainly in the following aspects:

a. Number of parameters: Standard Promise can only accept one parameter, while jQuery can pass multiple parameters

Copy code The code is as follows:

function asyncInJQuery() {
var d = new $.Deferred();
setTimeout(function() {
         d.resolve(1, 2);
}, 100);
Return d.promise()
}
asyncInJQuery().then(function(val1, val2) {
console.log('output: ', val1, val2);
});
// output: 1 2

b. Handling exceptions in result processing

Copy code The code is as follows:

function asyncInPromise() {
Return new Promise(function(resolve) {
​​​​ setTimeout(function() {
          var jsonStr = '{"name": "mt}';
            resolve(jsonStr);
}, 100);
});
}
asyncInPromise().then(function(val) {
var d = JSON.parse(val);
console.log(d.name);
}).then(null, function(err) {
console.log('show error: ' err.message);
});
// show error: Unexpected end of input
function asyncInJQuery() {
var d = new $.Deferred();
setTimeout(function() {
        var jsonStr = '{"name": "mt}';
         d.resolve(jsonStr);
}, 100);
Return d.promise()
}
asyncInJQuery().then(function(val) {
var d = JSON.parse(val);
console.log(d.name);
}).then(function(v) {
console.log('success: ', v.name);
}, function(err){
console.log('show error: ' err.message);
});
//Uncaught SyntaxError: Unexpected end of input

It can be seen from this that Promise performs result processing on the callback function and can capture exceptions during the execution of the callback function, but jQuery.Deferred cannot.

Statement
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
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

火了!新的JavaScript运行时:Bun,性能完爆Node火了!新的JavaScript运行时:Bun,性能完爆NodeJul 15, 2022 pm 02:03 PM

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

nodejs中lts是什么意思nodejs中lts是什么意思Jun 29, 2022 pm 03:30 PM

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

深入浅析Nodejs中的net模块深入浅析Nodejs中的net模块Apr 11, 2022 pm 08:40 PM

本篇文章带大家带大家了解一下Nodejs中的net模块,希望对大家有所帮助!

怎么获取Node性能监控指标?获取方法分享怎么获取Node性能监控指标?获取方法分享Apr 19, 2022 pm 09:25 PM

怎么获取Node性能监控指标?本篇文章来和大家聊聊Node性能监控指标获取方法,希望对大家有所帮助!

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools