2015-09-10 38 views
-1

您能否请解释下面的代码中出现了什么问题。TypeError:无法调用Nodejs Promises中未定义的方法'then'

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

+2

' readFile'不会返回一个承诺,为什么你认为它呢? – Bergi

+0

我正在尝试base64加密的文件,因为你可以看到,但我是承诺的新手。那么处理这种情况的理想是什么? – Mithun

+0

@Mithun你按照[这里](https://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback)所述的回调传递也是“但我对承诺是新的”,也许,但是再次没有承诺这里。 –

回答

1

你必须创建一个异步函数返回一个承诺或使用一个承诺库像bluebird.js

香草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); 
    }); 
+1

那么,如果你使用的是蓝鸟,你应该简单地使用'promsifyAll' – Bergi

2

readFile不返回的承诺。 NodeJS大体上早于Promise的广泛使用,并且大多使用简单的回调代替。

读取该文件,你在一个简单的回调传递,因为这个例子从文档显示:

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

有可用的promisify-node module一个包装了启用承诺-API标准模块的NodeJS。从它的文档实例:

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几年前)。

相关问题