【问题标题】:How to return to parent function in JavaScript [duplicate]如何在JavaScript中返回父函数[重复]
【发布时间】:2019-08-11 02:54:33
【问题描述】:

我目前有以下函数,我想将"aaa"返回给父函数(getStream),这是我的atm代码:

module.exports.getStream = (figure) => {
    plotly.plot(figure, imgOpts, function(err, stream) {
        if (err) {
            console.log(err);
            return "error";
        }

        return "aaa";
    });
};

然而,现在它返回undefined。解决该问题的最佳解决方案是什么?

【问题讨论】:

  • “它返回undefined”是什么意思?它是什么”?您希望plotly.plot 调用返回"aaa" 还是希望getStream 返回它?
  • 通过在plotly.plot 中使用回调,我假设它是一个异步函数?如果是这样,您需要等待它解决。查看Promisesasync/await

标签: javascript node.js node-modules


【解决方案1】:

问题是getStream 没有返回任何东西(因此它的返回值为undefined)。您必须在 plotly 之前添加 return 或删除花括号。您还必须返回一个承诺,因为plotly.plot 方法的第三个参数是一个回调函数(我猜)。

module.exports.getStream = (figure) =>
  new Promise((resolve, reject) => {
    plotly.plot(figure, imgOpts, function(err, stream) {
        if (err) {
            console.log(err);
            reject("error");
        }

        resolve("aaa");
    });
  })

然后在应用程序的某个地方:

const foo = async () => {
  try {
    const result = await getStream(figure)
    console.log(result) // 'aaa'
  } catch (err) {
    console.log(err)  // 'error'
  }
}

【讨论】:

  • js module.exports.getStream = (figure) => plotly.plot(figure, imgOpts, function(err, stream) { if (err) { console.log(err); return "error"; } return "aaa"; }); 仍然返回 undefined 而不是 "aaa" / 错误。
  • 哦,好吧,我没有意识到plotly.plot 方法不会返回任何东西。所以我猜你必须使用一个承诺,我会更新我的答案
猜你喜欢
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 2013-10-23
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
相关资源
最近更新 更多