【问题标题】:TypeError: Cannot call method 'then' of undefined in Nodejs PromisesTypeError:无法调用 Nodejs Promises 中未定义的方法“then”
【发布时间】:2015-09-10 21:35:14
【问题描述】:

你能解释一下下面这段代码有什么问题吗?

   var promise = fs.readFile(file);

   var promise2 = promise.then(function(data){
      var base64 = new Buffer(data, 'binary').toString('base64');
      res.end("success");
   }, function(err){
      res.end("fail");
   });

它的抛出错误为TypeError: Cannot call method 'then' of undefined

【问题讨论】:

  • readFile 不返回承诺,你认为为什么会这样?
  • 如您所见,我正在尝试对文件进行 base64 加密,但我对 promises 不熟悉。那么处理这种情况的理想情况是什么?
  • @Mithun 你传入一个回调,如 here 所述,还有“但我对 Promise 很陌生”,也许,但同样,这里不涉及 Promise。

标签: javascript node.js file callback promise


【解决方案1】:

readFile 不返回承诺。总的来说,NodeJS 早于 Promise 的广泛使用,并且主要使用简单的回调。

要读取文件,请传入一个简单的回调,如文档中的此示例所示:

fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});

有一个 promisify-node module 可用,它将标准 NodeJS 模块包装在一个支持承诺的 API 中。来自其文档的示例:

var promisify = require("promisify-node");
var fs = promisify("fs")
fs.readFile("/etc/passwd").then(function(contents) {
  console.log(contents);
});

我应该强调我不知道它也没有使用过它,所以我不能说它的工作效果如何。它似乎使用nodegit-promise“具有同步检查的基本 Promises/A+ 实现”,而不是 JavaScript 的 Promise(这是公平的;它比 JavaScript 的 Promise 早几年)。

【讨论】:

    【解决方案2】:

    您必须创建一个返回 Promise 的 Async 函数或使用像 bluebird.js 这样的 Promise 库

    原版 JS

     var promise = readFileAsync();
        promise.then( function(result) {
            // yay! I got the result.
        }, function(error) {
            // The promise was rejected with this error.
        }
    
        function readFileAsync()
        {
           var promise = new Promise.Promise();
           fs.readFile( "somefile.txt", function( error, data ) {
                if ( error ) {
                    promise.reject( error );
                } else {
                    promise.resolve( data );
                }
            });
    
            return promise;
        }
    

    使用 BlueBird.js

     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);
        });
    

    【讨论】:

    • 好吧,如果你使用的是 Bluebird,你应该简单地使用 promsifyAll
    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多