在 NodeJS 中,我有一个像这样的对象,
var scope = { word: "init"};
使用 Object.defineProperty as described in MDN我将 get()
函数重写成这样,
Object.defineProperty(scope, 'word', {
get: function() {
return Math.random();
}
});
每次我在控制台中 scope.word
时都会正确返回一个新的随机数。但是,该函数还必须从具有回调的函数中获取数据。所以它的工作方式很像 setTimeout
,
Object.defineProperty(scope, 'word', {
get: function() {
setTimeout(() => {
return Math.random();
}, 1000)
}
});
现在每次我执行 scope.word
我都会得到,
undefined
因为get()
函数是同步的。这当然可以通过返回一个 Promise 来解决,
Object.defineProperty(scope, 'word', {
get: function() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(Math.random());
}, 1000)
});
}
});
但是我需要做 scope.word.then(...)
但是我们正在构建的整个想法是开发人员只需要 scope.word
就像它是一个简单易用的变量一样。 就像 Angular 的 $scope 或 VUE.js 的“数据”。
如何让 get()
函数返回实际值,而不是 Promise?是否可以使用 async
/await
来解决问题?怎么办?
最佳答案
一种解决方案是像这样传递回调函数。
const scope = {}
Object.defineProperty(scope, 'word', {
value: (cb)=>{
setTimeout(() => {
cb(Math.random())
}, 1000)
}
});
scope.word(res=>console.log(res))
关于javascript - 如何在不返回 Promise 的情况下从对象的 `get()` 获取异步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54881525/