node异步i/o 快速promisify
2020-12-17 本文已影响0人
凡凡的小web
fs异步
//bluebird的promisify
https://www.cnblogs.com/winyh/p/6676630.html
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));
fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
console.log("Successful json");
}).catch(SyntaxError, function (e) {
console.error("file contains invalid json");
}).catch(Promise.OperationalError, function (e) {
console.error("unable to read file, because: ", e.message);
});
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Promise = require("bluebird");
UserSchema = new Schema({
username: String,
password: String,
created_at: {
type: Date,
"default": Date.now
}
});
var User = mongoose.model('User', UserSchema);
Promise.promisifyAll(User);
Promise.promisifyAll(User.prototype);
//使用
User.findAsync({username: username}).then(function(data) {
...
}).catch(function(err) {
...
});
开源项目里的promise
ioredis
mongoose && mongoskin
redis.get('foo').then(function (result) {
console.log(result);
});
fs模块promise可以使用fs-extra,基础上又扩展了方法
https://github.com/jprichardson/node-fs-extra
https://www.xiejiahe.com/blog/detail/5b52fca1df53a14006035e1e