-1

I have the following function at the moment, and I want to return "aaa" to the parent function (getStream), this is the code I have atm:

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

        return "aaa";
    });
};

Right now, however, it returns undefined. What's the best solution to solve that problem?

  • What do you "it returns `undefined`"? What is "it"? Do you want the `plotly.plot` call to return `"aaa"` or do you want `getStream` to return it? – Jonathan Lam Aug 10 '19 at 18:36
  • By the use of a callback in `plotly.plot`, I'm assuming it's an asynchronous function? If so, you need to wait for it to resolve. Look into `Promises` and `async/await`. – Will Alexander Aug 10 '19 at 18:37

1 Answers1

1

The problem is that getStream does not return anything (therefore its return value is undefined). You have to add return before plotly or just remove curly braces. Also you'll have to return a promise, because that third argument of plotly.plot method is a callback function (I guess).

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

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

and then somewhere in the app:

const foo = async () => {
  try {
    const result = await getStream(figure)
    console.log(result) // 'aaa'
  } catch (err) {
    console.log(err)  // 'error'
  }
}
BorisTB
  • 1,686
  • 1
  • 17
  • 26
  • ```js module.exports.getStream = (figure) => plotly.plot(figure, imgOpts, function(err, stream) { if (err) { console.log(err); return "error"; } return "aaa"; }); ``` still returns `undefined` and not `"aaa"` / error. – Lukasz Dabrowski Aug 10 '19 at 18:41
  • Oh ok, I didn't realise that `plotly.plot` method doesn't return anything. So you'll have to use a promise I guess, I'll update my answer – BorisTB Aug 10 '19 at 18:45