A B
A B

Reputation: 131

Cracking open results returned by Ember peekAll

I'm playing around with peekAll(), trying to understand how it works for the ultimate purpose of iterating through the results.

In a route's model hook, I have:

var peekAllResults = this.store.peekAll('position');
console.log("peekAllResults = ", peekAllResults);
var peekAllResultsContent = peekAllResults.get('content');
console.log("peekAlLresultsContent = ", peekAllResultsContent);

This is returning data, as expected based on what I've got in my app.

In particular, here's what shows in the console:

enter image description here

So far so good. There are 8 records as expected based on what I've got going on.

But when when I add:

console.log("peekAllResultsContent.length=", peekAllResultsContent.length)

I get: peekAllResultsContent.length = 0

Same thing if I do peekAllResultsContent.get("length")

What is going on there?

I thought peekAll was a synchronous call that returned an array. Is there some trick to cracking it open and seeing what's actually in the array? I can't even get the length, so I figure I'm not on the right track.

Upvotes: 0

Views: 201

Answers (1)

Keo
Keo

Reputation: 1153

Everything is wrapped into Ember.Model objects so you won't see clear results from console.log. But there is no magic behind it. If the entities are already loaded into store you can get them via peekAll.

const positions = this.get('store').peekAll('position');
console.log('positions length', positions.get('length');

//we can iterate over them:
positions.forEach(position => {
  console.log(position.get('name'));
};

//we can filter them:
const southOnlyPositions = positions.filter(position => position.get('direction') === 'south');

and so on...

Btw: even for promises you are not supposed to access content. You get the result like this:

const promises = this.get('store').findAll('position');

promises.then(positions => {
  // positions here behave same as before
});

Upvotes: 1

Related Questions