你必須創建一個異步函數返回一個承諾或使用一個承諾庫像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);
});
' readFile'不會返回一個承諾,爲什麼你認爲它呢? – Bergi
我正在嘗試base64加密的文件,因爲你可以看到,但我是承諾的新手。那麼處理這種情況的理想是什麼? – Mithun
@Mithun你按照[這裏](https://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback)所述的回調傳遞也是「但我對承諾是新的」,也許,但是再次沒有承諾這裏。 –