Nodejs promise 工具包分享

Nodejs promise 工具包分享

原帖发在 CNode.js 论坛上, 见 https://cnodejs.org/topic/573b2d64fcf698421d20359d


听说 v8 已经着手实现 async/await 了, 可喜可贺

分享一波 promise 工具集

promise.map

跟 bluebird promise.map 一样的功能, 提供 concurrency, 这个实现的核心代码抄自很久之前的 async.parallelLimit https://github.com/magicdawn/promise.map

var map = require('promise.map');
var p = map(arr, function(item, index, arr){
  return getOtherPromise(item);
}, concurrency);

promise.delay

还是跟 bluebird 的功能一致, 实现一个 sleep 功能 https://github.com/magicdawn/promise.delay

const sleep = require('promise.delay');
sleep(100).then(function(){
  // blabla
});

promise.obj

类似 bluebird Promise.props, 实现 object 版本的 Promise.all https://github.com/magicdawn/promise.obj

const pobj = require('promise.obj');

const p = pobj({ x: Promise.resolve(‘x’), y: Promise.resolve(‘y’) });

p.then(function(o){ o.x // ‘x’ o.y // ‘y’ })

promise.retry

给一个异步函数, 增加重试功能, 支持普通错误 & 超时错误. 这个貌似 bluebird 里面没有? https://github.com/magicdawn/promise.retry

const pretry = require('promise.retry');
const TimeoutError = pretry.TimeoutError;
const RetryError = pretry.RetryError;
const fnWithRetry = pretry(fn, options);

promise.timeout

给一个异步函数加上超时处理 https://github.com/magicdawn/promise.timeout

var ptimeout = require('promise.timeout');

// a function will cost 20ms function test() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(20); }, 20); }); }

const test10 = ptimeout(test, 10); const test50 = ptimeout(test, 50);

// 10 timeout try { yield test10(); } catch (e) { e.should.be.ok(); e.should.be.instanceof(ptimeout.TimeoutError); e.message.should.match(/timeout/); e.timeout.should.equal(10); }

// 50 ok const _50 = yield test50(); _50.should.be.ok(); _50.should.equal(20);

promise.ify

类似 bluebird Promise.promisify, 支持简单的 promiseifyAll, 以及 noerr 处理没有 err 的 callback 情况 https://github.com/magicdawn/promise.ify

var promiseify = require('promise.ify');
var readFile = promiseify(fs.readFile, fs);

var Connection = require(‘mysql/lib/Connection’); promiseify.all(Connection.prototype);

好的, 为什么实现 bluebird 那些方法呢, 因为不想绑死在 bluebird 上, 有一些原因要去掉 bluebird 的时候不会因为它的一些有用的方法而舍不得. 有了这些小工具库,可以选择任意 Promise A+ 实现哦~都是使用的 global.Promise

注意 promise.retry 使用了 generator, 目标环境为 ES6, 其他的包都是 target 到 ES5 的, 就是 browserify or webpack 直接 require 即可, 不需要再次编译.


4 回复

几个都是 0 star. 不过不要因为这个就产生顾虑, 他们都是 100% coverage 的.


发出来还是 0 star … 看来我真是自娱自乐

关于Node.js中的Promise工具包,以下是一些值得分享的内容:

内置Promise

Promise是JavaScript中用于异步编程的一种解决方案,它代表了一个异步操作的最终完成(或失败)及其结果值。在Node.js中,你可以使用内置的Promise来处理异步操作。以下是一个简单的例子:

function asyncFunc() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('success');
    }, 1000);
  });
}

asyncFunc().then(result => console.log(result)).catch(error => console.error(error));

第三方工具包

除了内置的Promise,Node.js生态中还有许多增强Promise功能的第三方工具包。例如:

  1. fs-extra:增强了Node.js内置的fs模块,提供了更多文件系统操作方法,并且支持Promise调用方式。

    const fse = require('fs-extra');
    fse.readJSON('./a.json')
      .then(data => console.log(data))
      .catch(err => console.error(err));
    
  2. globby:一个增强型的glob工具,支持多模式匹配,并返回Promise对象。

    const globby = require('globby');
    globby(['**/*.js', '**/*.css']).then(files => console.log(files)).catch(err => console.error(err));
    

这些工具包可以大大提高你在Node.js中进行异步编程的效率和代码可读性。

回到顶部