9

I see a lot of questions (e.g. here or here, just in the past couple of hours) where the poster is making an Ajax call within a function (and doing something with the results in a callback) and doesn't understand why the results aren't available either later in the parent function or as the return value of the parent function. I.e. they don't understand that Ajax is asynchronous.

Unfortunately since they don't understand the problem, the questions are often phrased in very different ways -- they think they have an issue with variable definition, or return values, or scope. This makes it hard to close such questions as duplicates.

So, two questions: 1) if we were to close such questions as duplicates, is there a "canonical" answer that would be good to use, and 2) how do we deal with the fact that these are, in fact, duplicates (in terms of the deeper issue), but aren't phrased as such -- really aren't "exact duplicates" -- because of misunderstanding?

  • 1) yeah, probably. You should look for a good general version, such as "why is my return value null?" which highlights the asynchronous nature. 2) close them as dupes. – user1228 Dec 7 '11 at 18:45
  • 3) Answer them and then close them as Too Localized – user7116 Dec 7 '11 at 19:17
  • 1
    For these, I usually count on SLaKs to come around after a few minutes and welcome the OP to the world of async. – Andrew Whitaker Jan 6 '12 at 19:37
  • Perhaps this question should be migrated back to mSO – Travis J Jul 29 '14 at 23:54
2

lyI don't think there can be a canonical answer to mark everything a duplicate of as every question is asked in a different context, in a different way and likely has different symptoms and different issues. The OP would likely not feel like they got their situation explained appropriately if their question was just marked a duplicate of some other answer that attempts to explain asynchronous in general.

As I've answered a number of these questions myself with separately written answers each time. What I think is needed is a very good reference to point to that describes all the issues with asynchronous and offers both good code examples and common mistake code examples. That reference can then be cited along with a small amount of explanation related to the specific question.

I certainly do agree with you that this is a common issue as here are a few "asynchronous" answers I've provided:

| improve this answer | |
1

There is actually a canonical answer to this highly popular type of question for javascript. It is also the first result in the frequent tab for javascript on Stack Overflow (not that anyone looks there who is asking about these it seems).

The canonical answer is here: How do I return the response from an asynchronous call? by Felix Kling (243k rep)

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged .