美文网首页
node异步i/o 快速promisify

node异步i/o 快速promisify

作者: 凡凡的小web | 来源:发表于2020-12-17 22:46 被阅读0次

    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

    相关文章

      网友评论

          本文标题:node异步i/o 快速promisify

          本文链接:https://www.haomeiwen.com/subject/aywzgktx.html