Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array Push breaks loop?

I have the following Typescript class, with it's Click function, which is triggered by a button click, in my mobile app. The bit of interest is the todoItemTable.read, which goes and gets an array of ToDoItems from my cloud backend. The current code works and spits out the text of 8 todo items, but I want to store the text in an array, so if you see the commented out line where I push into todos, that was how I thought I woula pproach the issue. However, that line of code stos the loop running, so I get the first ToDo item logged twice and then nothing else. The application does't hang and there is no error.

export class HelloWorldModel extends Observable {
  public todos: any[]; 

  constructor() {
    super();
  }

  Click() {
    var client = new MobileServiceClient("https://example.azurewebsites.net");
    console.log("CLIENT");
    var todoItemTable = client.getTable("TodoItem");
    console.log("Table");
    this.todos = [];
    todoItemTable.read<TodoItem>().then(function (results) {
      // results is array of TodoItem-s
      console.log(results.length);
      console.log(results[0].text);
      for (let i of results) {
        console.log(i.text);
        //this.todos.push(i.text);
      }
    });
  }

}

What is going wrong?

like image 726
George Edwards Avatar asked Sep 04 '26 12:09

George Edwards


1 Answers

To work with the same scope use arrow functions, like this:

todoItemTable.read<TodoItem>().then((results) => {
  for (let i of results) {
    this.todos.push(i.text);
  }
});

See the Mozilla Developer Network on Arrow functions

like image 114
Cesar William Alvarenga Avatar answered Sep 06 '26 04:09

Cesar William Alvarenga