0

How can I get this object (tempObj) to be available outside of the function)?

The first console.log print it fine, but the other one gives an error that myJSON is not defined...

sensor.getAll(function (err, tempObj) {
var myJSON = JSON.stringify(tempObj);
console.log("Objekt "+ myJSON);
});

console.log(myJSON);
A.E
  • 3
  • 2

1 Answers1

-2

You need to declare myJSON outside of the function/closure instead of in it. You can create a variable with global or file scope (ES6) depending on your particular environment. If you want to use a callback.

var myJSON;
function callback() {
    console.log(myJSON);
}
sensor.getAll(function (err, tempObj) {
    myJSON = JSON.stringify(tempObj);
    console.log("Objekt "+ myJSON);
    callback();
});
  • That's only going to work if `sensor.getAll` is synchronous, but it has the signature of an asynchronous function. – Quentin Nov 19 '20 at 17:28
  • Correct. myJSON will be undefined until the sensor.getAll is called. You can use a callback inside the getAll function to trigger something to react to myJSON being set https://benohead.com/blog/2014/12/02/javascript-variables-asynchronous-callback-functions/ – Joshua Goldstein Nov 19 '20 at 17:35