I have a controller which calls a service, the service does an async work, when the work (Promise) is done I set a property on the controller's scope object.
function TodoController(TodosService) {
let self = this;
TodosService.fetchTodos().then((todos) => (self.todos = todos));
... other code here
}
The problem is that using async/await in the service does not update the html rendered elements after the promise is resolved, but using then works normally and updates the rendered elements with the fetched todos:
app.service("TodosService", function ($http) {
// This code does not work, it fetches the todos successfully and also the controller succesfully sets them as a property, but no visual change happens
// this.fetchTodos = async function () {
// let json = await $http.get("...");
// return json.data["todos"];
// };
// This code works normally as explained above
this.fetchTodos = () =>
$http
.get("...")
.then((json) => json.data["todos"]);
}
What is the difference between the two cases, because AFAIK (I'm new to JS) both an async function and $http.get(...).then(...) will return promises, so what am I missing here?
.then()will only return a promise if it actually has areturnstatement.returnin thethensection, but here I used arrow functions for brevity only. Also I want to mention that I printed the return value of both approaches (theasync/awaitand the.then) and both printedobject Promise, but why is one Promise updating the html visuals and the other is not?.then()callback. The containing function must return the result of the Promise chain, or else it returnsundefined.fetchTodosin theasync/awaitcase is not returning aPromise? I printed the return value offetchTodos()in the controller and in both cases a promise was returned and the callback was invoked after some waiting time?self.todosin that "other code here" block, that will not work. The call to.then()will return immediately, before the Promise is resolved.