In NodeJS, I have an object like,
var scope = { word: "init" };
Using Object.defineProperty as described in MDN I re-write the get()
function to be like this,
Object.defineProperty(scope, 'word', {
get: function() {
return Math.random();
}
});
Which correctly returns a new random each time I scope.word
in the console. However the function must also get data from a function with a callback. So it works pretty much like a setTimeout
,
Object.defineProperty(scope, 'word', {
get: function() {
setTimeout(() => {
return Math.random();
}, 1000)
}
});
Now everytime I do scope.word
I get,
undefined
Because the get()
function is synchronous. This can be of course solved by returning a Promise,
Object.defineProperty(scope, 'word', {
get: function() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(Math.random());
}, 1000)
});
}
});
But then I would need to do scope.word.then(...)
but the whole idea behind what we are building is that the developer only has to scope.word
like if it was a plain easy-to-use variable. Like an Angular's $scope or a VUE.js 'data'.
How can I make the get()
function return an actual value, not a Promise? Is it possible to workaround using async
/ await
? How?