V
V
vostotskiy2016-12-19 14:50:26
Angular
vostotskiy, 2016-12-19 14:50:26

What am I doing wrong with promise in AngularJS service?

Hello. Moved the data loading logic from the controller to a separate service. in the controller I call
vm.projects= reportsService.initReport( vm.id);
In the initReport method itself, the following code

function initReport(id) {
    getTimeTypes(isView).then(function(data){
        types = data;
    })
    console.log(types);
    return [
        types
    ]
}

The function to get the types processes the http request and returns an error or data
function getTimeTypes(isView){
            return restAPI.getTimeTypes()
                .then(
                    function( data ) {
                        var temp = [];
                        temp = parseResponse(data,isView);
                        if(temp.items && temp.items.length){
                            return temp.items;
                        }
                    }
                )
        }

In my case, it turns out that an empty types variable is returned in initReport (return fires, skipping initialization in then types), without waiting for this block to fire in the method
getTimeTypes(isView).then(function(data){
    types = data;
})

Please tell me why this code fragment is ignored, despite the presence of an asynchronous operation waiting block in it, and why the function returns the result before one of the commands is executed. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2016-12-21
@Casufi

https://habrahabr.ru/company/mailru/blog/269465/

A
Alexey Ukolov, 2016-12-19
@alexey-m-ukolov

Please tell me why this code fragment is ignored, despite the presence of an asynchronous operation waiting block in it, and why the function returns the result before one of the commands is executed.

Because that's what asynchrony is. What you are describing is synchronous code, you don't have it, so it doesn't have the behavior you expect.
Anything you can return from an async function is a promise. And further in the code, subscribe to its execution using .then().
function initReport(id) {
    getTimeTypes(isView).then(function(data){
        return [data];
    });
}

initReport(42).then(function (types) {
  console.log(types);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question