[英]NodeJS - Update an Object with returned Promise
我一直在兌現諾言。 不管我讀過多少個這個問題,我都無法解決。
我有一個具有部署(boolean)屬性的實驗室類/函數。 我想檢查實驗室是否已部署。 我已經有一個實驗室對象,因此我將其稱為lab.isDeployed()。 但是,當返回-返回true或false時,由於此異步“功能”,我不再可以訪問原始實驗室對象。
function lab(id) {
this.deployed = null; //This is the property.
this.isDeployed = function(){
return isLabDeployed(this.id, this.userID).then(function(data){
return data; //Where Data is a query to determine if its deployed.
});
}
這是從另一種方法調用的。
l.isDeployed().then(function(data){
expect(data).to.be.equal(false);;
});
我應該將實驗室對象傳遞回原始方法嗎? IE而不是返回上面的數據,我應該更新部署的屬性並將其返回嗎? 還是有另一種方法? 我試圖限制代碼,因為我希望得到解釋。
嘗試做這樣的事情:
this.isDeployed() = function() {
return new Promise(
(resolve, reject) => {
isLabDeployed(this.id, this.userID)
.then((data) => {
resolve(data);
});
}
);
然后,您可以將isDeployed函數作為Promise。
this.isDeployed()
.then((data) => {
// this is where you use your data.
});
否則,您可能要使用async / await
const data = await this.isDeployed()
基本上,您想解決作為承諾獲得的數據。 您甚至可以做一些簡單的事情。
this.isDeployed() = isLabDeployed(this.id, this.userId)
您仍然可以訪問l
對象
l.isDeployed().then(function(data){
expect(data).to.be.equal(false);
console.log(l.deployed) // lab object still accessible here
});
或使用async / await:
const data = await l.isDeployed()
console.log(l.deployed) // lab object still accessible here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.