Reputation: 1484
I've been struggling with promises. No matter how many phrasing of this question I read I can't sort it out.
I have a lab class / function which has a property of deployed (boolean). I want to check to see if the lab is deployed. I already have a lab object thus I call lab.isDeployed(). However when this returns - it returns true or false however I no longer can access the original lab object because of this asynchronous 'feature'.
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.
});
}
This is called from another method.
l.isDeployed().then(function(data){
expect(data).to.be.equal(false);;
});
Should I pass the lab object back to the original method? IE instead of returning data above, should I update the deployed property and return this? Or is there another way? I tried to limit the code as I was hoping for an explanation.
Upvotes: 0
Views: 520
Reputation: 5738
You're still be able to access l
object
l.isDeployed().then(function(data){
expect(data).to.be.equal(false);
console.log(l.deployed) // lab object still accessible here
});
Or with async/await:
const data = await l.isDeployed()
console.log(l.deployed) // lab object still accessible here
Upvotes: 1
Reputation: 38
Try doing something like this:
this.isDeployed() = function() {
return new Promise(
(resolve, reject) => {
isLabDeployed(this.id, this.userID)
.then((data) => {
resolve(data);
});
}
);
Then, you can call the isDeployed function as a promise.
this.isDeployed()
.then((data) => {
// this is where you use your data.
});
Otherwise, you might want to use async/await
const data = await this.isDeployed()
Basically you want to resolve the data you get as a promise. You might even be able to do something simple like.
this.isDeployed() = isLabDeployed(this.id, this.userId)
Upvotes: 1