1

If I have:

fetched_user.settings = null;
fetched_user.settings = JSON.stringify(settings);
$http.post('/api_endpoint', {
  val: fetched_user.settings
});

And JSON.stringify takes forever to execute, then my understanding is val: fetched_user.settings will likely be null since this is executed asynchronously (async newbie checkpoint: is this correct?).

Normally in these situations I would supply a callback function to be executed on completion of the long-running task, however, JSON.stringify() doesn't provide the option for a callback.

How should I write this?

4
  • Why would you want it to be async? Are user setting that big? Commented Jan 4, 2014 at 3:00
  • If you want it to be async, use web workers or setTimeout. Commented Jan 4, 2014 at 3:10
  • Nope, settings aren't big right now. But if it were async and I relied on the fact that it executed quickly while small, then should it ever take much longer to execute it would be a tricky bug to track down. Commented Jan 4, 2014 at 3:39
  • Async APIs usually either have a callback function passed as a parameter, or return a Promise. In either case, they wouldn't have a value ever directly available via the function return. So, it wouldn't work only some times. Commented Jan 4, 2014 at 13:21

1 Answer 1

6

JSON.stringify is not asynchronous so the $http.post line won't execute until stringification is done.

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

Comments

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.