"Nodejs development Crypto currency" 11:1 pictures skilled use of async components to resolve callback pits

Source: Internet
Author: User

About

"Nodejs development Crypto Currency" is a detailed development document for cryptocurrency products, involving all aspects of developing products using NODEJS, from front-end to backstage, from server to client, from PC to mobile, encryption and decryption. The code is completely open source and the article is free to share. Related Resources See http://ebookchain.org

Objective

As previously said, in the Nodejs world "everything is called back", learning to use Nodejs, the most unlikely to avoid is "callback" (with "recall" more intuitive). Cannot avoid, naturally want to face actively, therefore the open source community has appeared many code flow control solution. For example: Bluebird,q, and the async to be illustrated here.

This basic technology, the community documentation is extremely rich, obviously we do not need to repeat predecessors, so here to take the form of illustrations and classification, from the operational aspects. In addition, careful friends will also from the previous source analysis found that hundreds of millions of books using AYSNC, a comprehensive grasp of it, for understanding and coding, inefficient.

This is the https://npmjs.org rank of async on the top, except Lodash, that's it. Also, both Bluebird and Q are in the top 10, and it is basic to note that the Process Control component is standard for NODEJS processing callbacks.

Concept definition

Official Introduction:

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.

Simple translation: Async is a practical module that provides simple, straightforward, and powerful functions for handling asynchronous JS.

Process category

Just for good distinction, good memory, simple summary, the whole process should be the following three cases (not official description):

1. Basic process

From the point of view of the execution order of the program (multiple functions), including the basic processes of sequential execution, parallel execution, mixed execution, etc. If there is a dependency between functions, whether to limit the number of function execution, and so on, can continue to evolve many kinds.

2. Cycle Flow

A loop operation based on a condition that provides many functions, depending on how the condition is used.

3. Collection process

The above are all processed for one or a set of data. In reality, a large number of identical or similar data, such as a large number of files, addresses, centralized processing. Obviously, our first reaction is to loop through the above process, but Async provides a tool method (util) that asynchronously operates on a collection, such as foreach, called the "set process".

The concept of using a process can tell us clearly that when used async.forEach() , it is in asynchronous operation, which differs from simple forEach method invocation.

Usage category

Async provides more than 70 useful functions, all of which follow a convention: The asynchronous function you define (as a task), the last argument must be the callback function, the first argument of the callback function must be error, and the callback function is called once.

These functions are broadly divided into 3 categories, corresponding to the 3 classes above:

1. Basic type (one-time multitasking)

This corresponds to the basic process and Evolution process section, the operation of multiple tasks on a transaction, the invocation form is

async.funName(tasks, callback(error, results))

Here the Funname, including: series, parallel (Parallellimit), Waterfall, Auto (autoinject) and so on. Tasks can be in the form of an array, either in JSON or just one.

If all functions succeed, the results in callback will also correspond to tasks, converting the result of the executed function into an array or JSON form, and if there is a function error in the tasks, the subsequent execution is terminated, the callback is called, Error is the wrong message for the function, either results or contains only the results that have been executed, or contains the result placeholders for the non-executing function, or nothing that includes direct ignoring. As for what the results is, a log statement is naturally known and does not have to be documented.

2. Cyclic type (multiple single task)

Depending on the condition, you can invoke the following form

fn, callback)或async.doFunName(fn, test, callback)

The funname here include: whilst (Dowhilst), until (Dountil), during (doduring), Retry (retryable), Times (Timesseries, Timeslimit), Forever (the condition of the function test is not used, the condition is already implied).

The condition value here can be an expression function, or a specific number of times. To distinguish between FN and test order, very simple, as long as the meaning of English to understand can be, for example: Async.dowhilst (), must be first do, after whilst, so the parameters are naturally async.dowhilst (FN, test, callback)

3. Set type (multiple single task)

This official is not as a process statement, as a set of operating methods provided, is my personal understanding and fiction. I think it's better to accept and understand it as a process control. Therefore, it is good to mimic the cyclic invocation method above, as long as the condition test is changed to a set, and the collection is all used in array form.

async.funName(arr, iteratee, [callback])

Here's the funname, including:

each, eachSeries, eachLimitforforforEachOfLimitmap, mapSeries, mapLimitfilter, filterSeries, filterLimitreject, rejectSeries, rejectLimitreduce, reduceRightdetect, detectSeries, detectLimitsortBysome, someLimit, someSeriesevery, everyLimit, everySeriesconcat, concatSeries

Of course, Async also explicitly provides several other process controls, such as Compose,seq,applyeach (applyeachseries), queue (Priorityqueue), Cargo,iterator,race, and so on.

In addition, there are several util (tool) functions, such as: apply,nexttick,memoize,unmemoize,ensureasync,constant,asyncify,wrapsync,log,dir,noconflict , timeout, etc., which can greatly facilitate code writing and improve code performance.

Brain Map

The above explanations and methods, we all put in a brain map, combined with the scene, retrace, can quickly find the right way to deal with.

SOURCE Interpretation

Look Ebookcoin inside, async use it. Because in the "entrance Procedure app.js Interpretation", has already mentioned, here does not say, later encountered again explains.

Fun Practice

The Async official documentation provides a number of examples, simple and intuitive. Here, instead of giving an example, we present an interesting question for thought:

question : Can AYSNC be used for recursive calls, such as a crawler, a function that iterates through all the file information in a folder? Why?

Summarize

This is another cliché of technology sharing, but after writing it, the process management of asynchronous operations becomes clearer. AYSNC is good, but it is not omnipotent, it is useless for the code that repeats itself, because the callback that restricts the task is once. Follow-up, there will be opportunities to continue to study it in depth.

Link

This series of articles is updated immediately, to keep up to date, please follow the link below

Source Address: Https://github.com/imfly/bitcoin-on-nodejs

ebook reading: http://bitcoin-on-nodejs.ebookchain.org

Reference

Official Async Documentation

Promise of the latest technology stack of node. js

JavaScript Promise Mini-book (Chinese version)

"Nodejs development Crypto currency" 11:1 pictures skilled use of async components to resolve callback pits

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.