未加星标

Avoid callbacks in Node.js with Bluebird promises

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

In this article: Common callback usage patterns would be replaced with idiomatic Bluebird

Required knowledge: Basic Node.js experience, basic experience with Promises

Basic usage sequence of tasks: CallbackSequence.js const fs = require ( 'fs' ); fs. readFile ( 'someFile.txt' , 'utf8' , function (err, fileContent) { if (err) { throw err; // Actually ends process } fs. readFile (fileContent, function (err, image) { if

(err) { throw err; }

doStuff

(image); }); });

VS.

PromiseSequence.js const Promise = require ( 'bluebird' ); const fs = Promise . promisifyAll ( require ( 'fs' )); fs. readFileAsync ( 'someFile.txt' , 'utf8' ) . then (fileContent => fs. readFileAsync (fileContent)) . then (doStuff); . catch (err =>

{

// Handle all errors in one place

});

As we can see, maximal nesting level is reduced. Error handling point is well-defined, so we can’t make a mistake while handling errors like passing error to bad higher-level callback.

Branching

Promise based solution isn’t silver-bullet. To be honest I had to include common use case of branching when Promise based solution is only barely better than callback based flow.

BranchingCallback.js const basicArithmeticsAsService = require ( 'fictional-service' ); basicArithmeticsAsService. add ( 2 , 2 , (err, response) => { if (err) { return someCallback ( new TypeError ( 'Network issues' : + err.message)); } if (response. status === 200 ) { return basicArithmeticsAsService. multiply (response. body , 4 , (err, response) => { if (err) { return someCallback ( new TypeError ( 'Network issues' : + err.message)); } else if (response. status === 200 ) { return someCallback ( null , response. body ) } else { someCallback ( null , NaN ); } }) } else { someCallback ( null

,

NaN

); } });

VS.

BranchingPromise.js const basicArithmeticsAsService = require ( 'fictional-service' ); basicArithmeticsAsService. addAsync ( 2 , 2 ) . then ((response) => { if (response. status === 200 ) { return basicArithmeticsAsService. multiplyAsync (response. body , 4 ) . then (response => { if (response. status === 200 ) { return response. body ; } else { return NaN ; } }) } else { return NaN ; } }) . catch (err => { throw new TypeError ( 'Network issues'

: +

err.message); });

Async.js

Async.js became the industry standard for handling callbacks before Promises went viral. Today, most of async.js utilities can be replaced with idiomatic usage of advanced Promise implementations, with all of it richness promisification, convenient adapters for callbacks, long stack traces.

Let’s analyze basic asynchronous flows:

AsyncFilter.js const fs = require ( 'fs' ); const async = require ( 'async' ); async . filter ([ 'file1' , 'file2' , 'file3' ], function (filePath, callback) { fs. access (filePath, function (err) { callback ( null , ! err) }); }, function

(err, results){

// results now equals an array of the existing files

});

VS.

BluebirdFilter.js const Promise = require ( 'bluebird' ); const fs = Promise . promisifyAll ( require ( 'fs' )); Promise . filter ([ 'file1' , 'file2' , 'file3' ] , path=>fs. accessAsync (path)) . then

(results

=>

{ });

Bluebird exposes common array operations like map , filter , each . These methods take 3arguments array (or Promise resolving to array), function applied to each element and concurrency maximal number of functions running at once, in manner similar to async.fnLimit family.

Some async.js methods for collections can’t be emulated using basic Promise-based code methods like ‘sortBy’, ‘transform’ tend to be pain in ass. We’ll discuss how to marry async.js and Bluebird later.

Retry

It’s often convenient to retry failed task. It’s quite easy to write in synchronous manner, but writing it in asynchronous way can be mind-boggling, especially when concurrency or parallelism comes in the hand.

RetryCallback.js const async = require ( 'async' ); retry ( 5 , done => getResource (url, done), (err, result) => { if

(err)

throw

err; })

VS.

RetryPromise.js const async = require ( 'async' ); function retry (n = 5 , task) { return Promise . resolve (). then (task). catch (err => { if (n > 1 ) return retry (n - 1 , task); throw err; }); } retry (() =>

getResourceAsync

(url));

Bluebird offers better solution than callback based approach, because of it’s superior resource management. Consider this code:

RetryResourceCallback.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: Node.js
分页:12
转载请注明
本文标题:Avoid callbacks in Node.js with Bluebird promises
本站链接:http://www.codesec.net/view/481267.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(30)