📜 ⬆️ ⬇️

Asynchronous Programming: High Level Primitives

After the appearance of the Twisted asynchronous framework, the concept of delayed result (continuable) became very popular.

First of all, I recommend reading the articles: Asynchronous programming: the concept of Deferred , Deffered for JavaScript .

But using deferred results is not very convenient without higher level abstractions. And now we have a Do frame.
')
Now we can perform the following actions:

Perform several actions in parallel


// Multiple arguments
Do . parallel (
Do . read ( "/etc/passwd" ) ,
Do . read ( __filename )
) ( function ( passwd , self ) {
// Do something
} , error_handler ) ;

// Single argument
var actions = [
Do . read ( "/etc/passwd" ) ,
Do . read ( "__filename" )
] ;
Do . parallel ( actions ) ( function ( results ) {
// Do something
} , error_handler ) ;



Perform several actions in sequence.


// Multiple arguments
Do . chain (
Do . read ( __filename ) ,
function ( text ) {
return Do . save ( "newfile" , text ) ;
} ,
function ( ) {
return Do . stat ( "newfile" ) ;
}
) ( function ( stat ) {
// Do something
} , error_handler ) ;

// Single argument
var actions = [
Do . read ( __filename ) ,
function ( text ) {
return Do . save ( "newfile" , text ) ;
} ,
function ( ) {
return Do . stat ( "newfile" ) ;
}
] ;
Do . chain ( actions ) ( function ( stat ) {
// Do something
} , error_handler ) ;



Map source array to asynchronous result


var files = [ 'users.json' , 'pages.json' , 'products.json' ] ;
function load_file ( filename , callback , errback ) {
fs. read ( filename ) ( function ( data ) {
callback ( [ filename , data ] ) ;
} , errback ) ;
}
Do . map ( files , load_file ) ( function ( contents ) {
// Do something
} , error_handler ) ;


Filter array asynchronously


var files = [ 'users.json' , 'pages.json' , 'products.json' ] ;
function is_file ( filename , callback , errback ) {
fs. stat ( filename ) ( function ( stat ) {
callback ( stat. isFile ( ) ) ;
} , errback ) ;
}
Do . filter ( files , is_file ) ( function ( filtered_files ) {
// Do something
} , error_handler ) ;



In addition, wrappers for node.js are provided. Project on github .

Source: https://habr.com/ru/post/84709/


All Articles