node的模块包装为promise写法

1. const Promise = require('bluebird')

const fs = Promise.promisifyAll(Promise.promisify(require('fs')))

fs.readFileAsync('./test.js').then(function(data){
  console.log(data);
}).catch(console.log);

2.针对node  npm部分模块,比如xml2js,不支持bluebird包装的形式,解决办法

const xml2js = require('xml2js')

const Parser = new xml2js.Parser()

const parseStringAsync = xml => {
return new Promise((resolve, reject) => {
Parser.parseString(xml, (err, result) => {
if (err) {
reject(err)
} else {
resolve(result)
}
})
})
}

原文地址:https://www.cnblogs.com/qiyc/p/8746228.html