【问题标题】:Call to async function not working as exptecd调用异步函数不能作为 exptecd
【发布时间】:2015-07-30 18:10:01
【问题描述】:

我使用以下代码,但代码没有进入 if 语句

function getContent(key) {
    var filePath = path.join(__dirname, '../test.txt');
    fs.readFile(filePath, 'utf8', function (err, data) {
        if (err) {
            return console.log(err);
        }
        ....
        var fileKeyValObj = {};
        return fileKeyValObj[key];
    });
}

我能够通过调试访问上一个方法的返回,并且它工作正常... 这里的函数没有到达 if

getContent('web', function (cmd) {
    if (typeof cmd !== 'undefined') {

这里的关键是我发送的网页,我看到 getContent 的返回值是正确的。

我看到了这篇文章,但我认为我做了同样的事情,我在这里错过了什么吗? How do I return the response from an asynchronous call?

顺便说一句,在这种情况下,建议使用 promise??? 像蓝鸟

【问题讨论】:

  • 从异步回调返回数据不是你想要的。这只是返回到文件系统代码的内部,而不是返回到您的任何代码。您不能尝试使异步操作突然同步。你就是不能。 getContent() 需要返回一个 Promise 或接受一个回调,您可以在结果可用时调用。

标签: javascript asynchronous callback promise bluebird


【解决方案1】:

问题是你的回调中fs.readfilereturn 值不是其包含函数getContent 的有效返回值。

当您将回调传递给fs.readFile 时,您传入的函数将排队fs.readFile 完成时运行。简单来说,getContent 进行排队,然后说“我的工作完成了!”并返回 (void),但 fs.readfile 在运行回调之前等待自己完成。

fs.readfile 运行它的回调时,它脱离了getContent 的上下文。它会返回,但“没有人会在那里”来获取返回值。

您可以做的是将回调传递给getContent,然后将其传递给fs.readFile

function getContent(key, callback) {
    var filePath = path.join(__dirname, '../test.txt');
    fs.readFile(filePath, 'utf8', callback);
}

getContent('web', function (error, data) {
    if (!error) {
        ... //Put your code here!
    } else {
        console.log(error);
    }  
});

现在,getContent 将在 fs.readFile 完成时运行它的第二个参数 function (error, data)

【讨论】:

  • 谢谢,但是在 readfile 之后还有我应该使用的附加逻辑,我应该把它放在哪里?
  • 好的,在这种情况下我应该在回调中添加什么?
  • @JhonDree:您应该在当前放置 return 语句的位置调用 callback
  • @Bergi- 有点困惑你能举个例子吗?如果你能帮助承诺它会更好......
  • 当我调用getContent 时,我传入两个参数:webfunction (error, data)...。第二个参数在getContent 函数参数中变为callback。然后我们将相同的函数传递给fs.readFile 的第二个参数callback
猜你喜欢
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2018-09-07
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
相关资源
最近更新 更多