How to send a return form a callback function to the main function

倖福魔咒の 提交于 2019-12-01 12:34:32

问题


I have this fiddle http://jsfiddle.net/jdsans/38GFS/ which I was trying to workout but I could not send return for the callback function to the main function. The callback function contains end return value exactly what I want but its not returning back.

When I use the document.write() function to print the return value then I get the exact value printed that I want but as I said earlier it doesn't gets returned.

Please can anybody work with this fiddle to show me a working example. I have added more details in the fiddle as comments so that you don't have any problem understanding me.


回答1:


Looks like you're trying to have an asynchronous callback return a value (to a "synchronous" function call). That is like trying to captain a boat on dry land. The paradigms don't fit.

The concept of "return a value" only exists in a synchronous model. Where one function calls another, and values can be manipulated and returned. But your value that you want returned exists in a function callback. Which means that your entire execution thread will execute before the callback function, including the part where you save the returned value.

You need to think asynchronously. Don't return values, use them to call other functions that perform the necessary work.

I'll try and illustrate. Let's say I have code:

  1. Do something
  2. Call async function with a callback that returns a value
  3. Use the return value to print on the screen

The idea of async is that 1-3 execute before the callback is called. That's why it's called a callback!! So 3 will execute before we have the value. That doesn't make sense. Instead you need to change your code to execute:

  1. Do something
  2. Call asynch function with callback that uses a value and performs 3 from above.


来源:https://stackoverflow.com/questions/6883648/how-to-send-a-return-form-a-callback-function-to-the-main-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!