I need to make an api call that returns me a response of id's and values associated with it. The promise then resolves and returns a true or false if the id queried was found or not found.
How can i achieve this? New to using promises. As is promises seem confusing
here is the end point on consuming the API, UserService returns an array of id's and salaries. I need to check if the id exists and the salary matches to the query and then the promise needs to resolve to true or false.
here is the object of id's and incomes
[{
"id": 1,
"name": "Primary",
"sal": [{
"id": "1",
"sal": "10"
}, {
"id": "2",
"sal": "20"
}]
},{
"id": 2,
"name": "Secondary",
"sal": [{
"id": "1",
"sal": "100"
}, {
"id": "2",
"sal": "200"
}
]
}];
UserService.hasUserValue(id, income).then(function(qualifiesforlowIncome){
var isLowIncome = qualifiesforlowIncome
}
qualifiesforlowIncome is a boolean that returns a true or false. I am using angular so in this case should i do a $q.defer and return a defer.promise ?
A little unclear on this
Sure, all you need to do is add a then
case which determines if any of the objects match the query then return true
or false
from it. That value will get carried into the next then
case.
In this example, I'm using the some
method to see if any of the objects in the array match the condition.
Promise.resolve([
{
id: 1
},
{
id: 2
},
{
id: 3
}
])
.then(results =>
results.some(r => r.id === 2)
)
.then(foundResult => console.log(foundResult));
Or rewritten in ES5:
Promise.resolve([
{
id: 1
},
{
id: 2
},
{
id: 3
}
])
.then(function(results) {
return results.some(r => r.id === 2);
})
.then(function(foundResult) {
console.log(foundResult);
});
This works exactly the same even if you return a Promise which later resolves.
Promise.resolve([
{
id: 1
},
{
id: 2
},
{
id: 3
}
])
.then(results =>
// Return a promise, delay sending back the result
new Promise((resolve, reject) => {
setTimeout(() =>
resolve(results.some(r => r.id === 2)),
500
);
})
)
.then(foundResult => console.log(foundResult));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With