2015-09-10 37 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幾年前)。

相關問題