javascript - reslover function doesn't work for promise object in Node.js -
i'm trying use promise
in node.js read files, return promise
got {}
. code bellow:
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; }
the output is
app-0 readjsonfile called app-0 {} app-0 json ok [...the json string...]
i have no idea why console.log(promise)
null.
with codes above nothing happened in resolver function. can right output console.log("json ok", data);
nothing console.log("read ok", userlist);
my node's version 0.12 support promise.
it isn't null
. per output, it's showing empty object.
while console.log()
behavior not governed accepted standard, seeing because promise object has no publicly enumerable properties console.log()
has nothing show. doesn't mean promise object empty.
the better test whether readjsonfile(readpath).then(...)
works. if so, valid promise object , logging confused.
Comments
Post a Comment