Reputation: 1714
The below data is returned from the request()
library.
var data = [{
service: "trains",
...
}, {
service: "buses",
...
}]
I have the following code on a NodeJS application.
request(options)
.then(data => {
data.forEach(record => {
if (record.service !== 'buses') {
return next('You do not have permission to access buses.')
}
return next()
})
})
.catch(err => next(err))
So when this code runs on Node it always evaluates to false? This is odd to me because running this without the request and just using the raw response directly seems to work ok? I guess this is an issue with async behavior?
Upvotes: 0
Views: 905
Reputation: 1267
You're looping through all the elements of the array, so if the first element does not match 'buses', it will result in 'You do not have permission to acces buses'.
I think what you're looking for is a method to check if an element exists in an array. In your case something like Array.filter
:
.then(data => {
if (data.filter(el => el.service === 'buses').length === 0) {
return next('You do not have permission to access buses.');
}
return next();
})
Upvotes: 3