这个问题在这里已经有了答案:
如何返回来自异步调用的响应? 33个答案在同一个文件夹中,我有3个不同的文件,内容如下: •index.js
const getToken = require('./getToken.js'); console.log(getToken.getToken());getToken.js
const FS = require('fs'); //a library to read files module.exports = { getToken: function (){ FS.readFile('./token.txt', 'utf8', function (err, data) { if (err) { console.error(err); } else { console.log('Token is : ' + data); return data; } }); } }•token.txt
foo我使用NodeJs,fs,一个库来读取文件和一个Discord库。 我得到输出:
undefined //result of index.js Token is : foo //result of getToken.js代码工作正常,除了令牌没有正确地给予主js文件(index.js)即使它被正确读取。 这段代码有什么问题? 为什么console.log()的结果是错误的?
谢谢。
This question already has an answer here:
How do I return the response from an asynchronous call? 35 answersIn the same folder I have 3 different files with the following content : • index.js
const getToken = require('./getToken.js'); console.log(getToken.getToken());• getToken.js
const FS = require('fs'); //a library to read files module.exports = { getToken: function (){ FS.readFile('./token.txt', 'utf8', function (err, data) { if (err) { console.error(err); } else { console.log('Token is : ' + data); return data; } }); } }• token.txt
fooI'm using NodeJs, fs, a library to read files and a Discord library. I get as output :
undefined //result of index.js Token is : foo //result of getToken.jsThe code is working fine except that the token isn't given correctly to the main js file (index.js) even if it's read properly. What's wrong with this code? Why do the results of console.log() are in the wrong ordrer?
Thanks.
最满意答案
欢迎来到异步世界。 在异步操作(fs.readFile为异步)后返回值时,您需要使用回调或承诺;
使用回调将如下所示:
module.exports = { getToken: function (callback){ FS.readFile('./token.txt', 'utf8', function (err, data) { if (err) { callback(err); } else { console.log('Token is : ' + data); callback(null, data); } }); } } //Other file const getToken = require('./getToken.js'); getToken.getToken(function(err, result){ if(err) return console.log(err); console.log(result); });Welcome to the async world. You need to use callbacks or promises when returning values after an async operation (fs.readFile is async);
Using callback would be like this:
module.exports = { getToken: function (callback){ FS.readFile('./token.txt', 'utf8', function (err, data) { if (err) { callback(err); } else { console.log('Token is : ' + data); callback(null, data); } }); } } //Other file const getToken = require('./getToken.js'); getToken.getToken(function(err, result){ if(err) return console.log(err); console.log(result); });更多推荐
发布评论