0

I have a data set that I need to loop though and alter. it can take sometime and I have a little spinner running on the site. when I hit the loop it blocks the process. I would like to see if I can use $q to fix this. I can use $q with http calls and that seem to work fine.

angular.forEach(data, function (d) {
    d.name = "..." + d.name;
})
return data

is $ string the right way to do this? is there a better way? Thanks Danny

1
  • Where's the asynchronous part? Commented Feb 22, 2016 at 17:56

2 Answers 2

1

You're still going to block even if you wrapped it in a promise, or $q. It doesn't block during http request because another discrete machine is running the process, not your javascript thread. Javascript is single threaded, so it can't do multiple things at once. So even if you wrapped your forEach in a resolve, it will block. So here are some solutions.

1) Create a web worker
2) Split the array in smaller chunks and use a timeout to iterate over parts of the array allowing other process to run during the timeouts.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use $timeout to allow browser to show your spinner before running your loop.

function asyncLoop() {
    return $timeout(function () {
        return angular.forEach(data, function (d) {
            d.name = "..." + d.name;
        });
    }, 0, false); // Omit second and third arguments if you need to trigger a $digest() cycle
}

// show spinner

asyncLoop().then(function onAsyncLoopDone(data) {
    // do something with data
    // hide spinner
});

2 Comments

You do not need the deferred variable. In asyncLoop, you can simply return $timeout(function) { ... return data; }.
You are right, $timeout returns the promise itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.