Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return a promise that resolves to a boolean true or false if a value is found

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

like image 382
looneytunes Avatar asked May 24 '17 19:05

looneytunes


1 Answers

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));
like image 66
Mike Cluck Avatar answered Nov 18 '22 05:11

Mike Cluck