0

This is the code I have:

var items = [];

db.scan({TableName: "players"}, function(err, data) {
  for (var i = 0; i < 10; i++) {
      items.push(data.Items[i]);
  }
});

When I do...

console.log(items);

...it shows:

[]

When I do...

setTimeout(function() {
    console.log(items);
}, 1000);

...it shows:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}].

Is there a way to get a proper, filled array without the setTimeout?

Kon
  • 4,023
  • 4
  • 24
  • 38
AmazingDayToday
  • 3,724
  • 14
  • 35
  • 67

2 Answers2

1

I think you're misunderstanding the point of using callbacks. Your further code should go INSIDE of the callback, e.g.

db.scan({ TableName: "players" }, function (err, data) {
    var items = [];

    for (var i = 0; i < 10; i++) {
        items.push(data.Items[i]);
    }

    console.log(items);
});
Rubydesic
  • 3,386
  • 12
  • 27
  • Here it still shows `[]` and `items` won't be visible outside of the function! – AmazingDayToday Oct 08 '18 at 20:49
  • @AmazingDayToday The point is to than trigger the next set of code. The code you are trying to use needs to be called when the code is done running. Basically what you are trying to do is you order a pizza and as soon as you order it, you try to eat it. That is not possible. You need to use the callback to wait. When that is done, you call other code that needs to use it. – epascarello Oct 08 '18 at 21:00
1

Since db.scan is a callback function, any code that depends on the result of db.scan should be done in the callback.

Kon
  • 4,023
  • 4
  • 24
  • 38