标签云

微信群

扫码加入我们

WeChat QR Code

I have a function foo which makes an Ajax request. How can I return the response from foo? I tried returning the value from the success callback as well as assigning the response to a local variable inside the function and returning that one, but none of those ways actually return the response.function foo() {var result;$.ajax({url: '...',success: function(response) {result = response;// return response; // <- I tried that one as well}});return result;}var result = foo(); // It always ends up being `undefined`.


For a simple intro to Promises, this may be a good read: devopedia.org/promises

2019年08月26日20分13秒

[I was facing the same problem of asynchronous calling using axios and js, though it's not recommended to use a synchronous function, it works for certain situations. ](stackoverflow.com/questions/55239719/…)

2019年08月27日20分13秒

You can't make it work the way you want. though async/await would work. again it is promise based

2019年08月26日20分13秒

Pommy: If you want to use jQuery, you have to include it. Please refer to docs.jquery.com/Tutorials:Getting_Started_with_jQuery.

2019年08月26日20分13秒

In Solution 1, sub jQuery, I could not understand this line: If you use any other jQuery AJAX method, such as $.get, $.getJSON, etc., you have them to $.ajax. (Yes, I realize my nick is a tad ironic in this case)

2019年08月27日20分13秒

gibberish: Mmmh, I don't know how it can be made clearer. Do you see how foo is called and a function is passed to it (foo(function(result) {....});)? result is used inside this function and is the response of the Ajax request. To refer to this function, the first parameter of foo is called callback and assigned to success instead of an anonymous function. So, $.ajax will call callback when the request was successful. I tried to explain it a bit more.

2019年08月26日20分13秒

The Chat for this question is dead so I'm not sure where to propose outlined changes, but I propose: 1) Change the synchronous part to a simple discussion of why it's bad with no code example of how to do it. 2) Remove/merge the callback examples to only show the more flexible Deferred approach, which I think may also be a little easier to follow for those learning Javascript.

2019年08月26日20分13秒

Jessi: I think you misunderstood that part of the answer. You cannot use $.getJSON if you want the Ajax request to be synchronous. However, you should not event want the request to be synchronous, so that doesn't apply. You should be using callbacks or promisesto handle the response, as it is explained earlier in the answer.

2019年08月27日20分13秒

"synchronous requests block the execution of code and can leak memory and events" how can a synchronous request leak memory?

2019年08月26日20分13秒

MatthewG I've added a bounty on it in this question, I'll see what I can fish out. I'm removing the quote from the answer in the mean time.

2019年08月27日20分13秒

Just for the reference, XHR 2 allows us to use the onload handler, which only fires when readyState is 4. Of course, it's not supported in IE8. (iirc, may need confirmation.)

2019年08月27日20分13秒

Your explanation of how to pass an anonymous function as a callback is valid but misleading. The example var bar = foo(); is asking for a variable to be defined, whereas your suggested foo(functim() {}); doesn't define bar

2019年08月27日20分13秒

While this answer is nice (And we all love XHR2 and posting file data and multipart data is totally awesome) - this shows syntactic sugar for posting XHR with JavaScript - you might want to put this in a blog post (I'd like it) or even in a library (not sure about the name x, ajax or xhr might be nicer :)). I don't see how it addresses returning the response from an AJAX call. (someone could still do var res = x("url") and not understand why it doesn't work ;)). On a side note - it would be cool if you returned c from the method so users can hook on error etc.

2019年08月26日20分13秒

2.ajax is meant to be async.. so NO var res=x('url').. That's the entire point of this question and answers :)

2019年08月26日20分13秒

why is there a 'c' parameter in the functions, if on the first line you're overwriting whatever value it had? am i missing something?

2019年08月26日20分13秒

You can use parameters as a placeholder to avoid writing multiple times "var"

2019年08月26日20分13秒

cocco So you wrote misleading, unreadable code in a SO answer in order to save a few keystrokes? Please don't do that.

2019年08月26日20分13秒

This answer is completely semantic... your success method is just a callback within a callback. You could just have success: handleData and it would work.

2019年08月27日20分13秒

And what if you want to return the "responseData" outside of "handleData" ... :) ... how will you do it ... ? ... cause a simple return will return it to the "success" callback of the ajax ... and not outside of "handleData" ...

2019年08月26日20分13秒

Jacques & pesho hristov You missed this point. Submit handler is not the success method, it's the surrounding scope of $.ajax.

2019年08月26日20分13秒

travnik I didn't miss that. If you took the contents of handleData and put it in the success method it would act exactly the same...

2019年08月27日20分13秒

I don't know who voted it negative. But this is a work around which has worked in fact i used this approach to create a whole application.The jquery.ajax don't return data so its better to use the above approach. If it's wrong then please explain and suggest better way to do it.

2019年08月26日20分13秒

Sorry, I forgot to leave a comment (I usually do!). I downvoted it. Downvotes don't indicate factual correctness or lack of, they indicate usefulness in the context or lack of. I don't find your answer useful given Felix's which already explains this only in much more detail. On a side note, why would you stringify the response if it's JSON?

2019年08月27日20分13秒

ok.. Benjamin i used stringify, to convert a JSON Object to string. And thanks for clarifying your point. Will keep in mind to post more elaborate answers.

2019年08月26日20分13秒

And what if you want to return the "responseObj" outside of "successCallback" ... :) ... how will you do it ... ? ... cause a simple return will return it to the "success" callback of the ajax ... and not outside of "successCallback" ...

2019年08月26日20分13秒

A picture is worth a thousand words, Person A - Ask's person Bdetails to fix his car, in turn Person B - Makes Ajax Call and waits for response from server for car fixing details, when response is received, Ajax Success functioncalls the Person B function and passes the response as argument to it, Person A receives the answer.

2019年08月26日20分13秒

Would be great if you added lines of code with each image to illustrate the concepts.

2019年08月26日20分13秒

This does not explain how promises would solve this issue at all though.

2019年08月27日20分13秒

It doesn't work. promiseB will get 'undefined'

2019年08月26日20分13秒

jQuery and fetch methods both return promises as well.I would suggest revising your answer.Though jQuery's isn't quite the same (then is there, but catch isn't).

2019年08月26日20分13秒

Could you explain how the if (--expecting === 0) part of the code works please? The callback version of your solution is working great for me, I just don't understand how, with that statement, you are checking the number of responses completed. Appreciate it's just lack of knowledge on my part. Is there an alternative way that check could be written?

2019年08月26日20分13秒

Sarah: expecting starts out with the value of array.length, which is how many requests we're going to make. We know the callback won't be called until all of those requests are started. In the callback, if (--expecting === 0) does this: 1. Decrements expecting (we've received a response, so we're expecting one fewer response) and if the value after the decrement is 0 (we're not expecting any more responses), we're done!

2019年08月26日20分13秒

PatrickRoberts - Thanks!! Yes, copy-and-paste error, that second argument was completely ignored in that example (which is the only reason it didn't fail, since as you pointed out, results didn't exist). :-) Fixed it.

2019年08月27日20分13秒

There is nothing special about using an object here. It would work as well if you assigned he response directly to result. It works because you are reading the variable after the async function is complete.

2019年08月27日20分13秒

This is fine at global scope, but in some module context you probably want to ensure right context for the callback e.g. $.ajax({url: "api/data", success: fooDone.bind(this)});

2019年08月27日20分13秒

This is actually incorrect as React is one-way data binding

2019年08月27日20分13秒

MatthewBrent you are not wrong, but not right also, React props are object and if changed, they change throughout the application, but its not a way that React developer recommend to use it...

2019年08月27日20分13秒

recurf - It's not my project. You could try using their issue tracker.

2019年08月27日20分13秒

is this similar to generator functions? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…*

2019年08月27日20分13秒

Is this still relevant?

2019年08月27日20分13秒

You can make use of async-await if you're using some of the newest versions of node. If someone is stuck with older versions they can use this method.

2019年08月26日20分13秒

Unfortunately, this works only with functions that return promises – for example it doesn't work with Node.js API, which uses callbacks. And I wouldn't recommend using it without Babel, because not everyone uses "current browsers".

2019年08月26日20分13秒

MichałPerłakowski node 8 includes nodejs.org/api/util.html#util_util_promisify_original which can be used to make the node.js API return promises. Whether you have the time and money to support non-current browsers obviously depends on your situation.

2019年08月26日20分13秒

IE 11 is still a current browser in 2018, sadly and it doesn't support await/async

1970年01月01日00分01秒

IE11 is not a current browser. It was released 5 years ago, has a worldwide market share of 2.5% according to caniuse, and unless someone is doubling your budget to ignore all current tech then it's not worth most people's time.

1970年01月01日00分01秒

This is interesting. I like how it allows to code async calls the way you'd do it in other languages. But technically it's not real JavaScript?

2019年08月27日20分13秒

is this still considered the best way to return a value from a promise or async/await?

2019年08月27日20分13秒

edwardsmarkf Personally I don't think there's a best way as such. I use promises with then/catch , async/await as well as generators for async portions of my code. It largely depends on the context of usage.

2019年08月26日20分13秒

I would be interested to know why this is down-voted. It seems a good simple answer that has not been previously given.

2019年08月26日20分13秒

While this works, it's not really better than assigning to a global variable.

2019年08月26日20分13秒

There's nothing inherently asynchronous about callbacks or JavaScript.

2019年08月27日20分13秒

could that second function to reuseable??

2019年08月26日20分13秒

How do you use the results if oncolse,log is called? Doesn't everything just go to the console at that point?

2019年08月26日20分13秒