我尝试在Node.js中使用Promise
来读取文件,但return promise
获得了{}
。代码如下:
http.createServer(function(req, res) {
var readPath = __dirname + '/users.json';
readJSONFile(readPath).then(function(userList) {
insertUser(userList);
console.log("read ok", userList);
}, function(err) {
console.log(err);
});
}).listen(8888);
function readJSONFile(readPath) {
console.log("readJSONFile called");
var promise = new Promise(function(resolve, reject) {
fs.readFile(readPath, 'utf8', function(err, data) {
if(err) {
reject(err);
} else {
var json = JSON.parse(data);
console.log("json ok", data);
resolve(json);
}
});
});
console.log(promise);
return promise;
}
输出
app-0 readJSONFile called
app-0 {}
app-0 json ok [...the json string...]
我不知道为什么 console.log(promise)
为空。
上面的代码在解析器功能中没有发生任何事情。我可以使用console.log("json ok", data);
获得正确的输出,但console.log("read ok", userList);
我的节点的版本是0.12,它支持Promise。
答案 0 :(得分:2)
不是null
。根据你的输出,它只显示为一个空对象。
虽然console.log()
行为不受公认标准的约束,但您所看到的可能是因为promise对象没有公开的可枚举属性,因此console.log()
无法显示任何内容。这并不意味着promise对象实际上是空的。
更好的测试是readJSONFile(readPath).then(...)
是否确实有效。如果是这样,那么它显然是一个有效的promise对象,只是你的日志记录很混乱。