如何向main函数发送一个回调函数的回调函数 [英] How to send a return form a callback function to the main function

查看:274
本文介绍了如何向main函数发送一个回调函数的回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个小调 http://jsfiddle.net/jdsans/38GFS/ ,我是试图锻炼,但我不能发送返回的回调函数到主要功能。



当我使用document.write()函数打印返回值,然后我得到



请让任何人使用这个小提琴给我一个工作示例。

解决方案

看起来像你'试图让一个异步回调返回一个值(到一个同步函数调用)。这就像试图在干陆上上船一样。范例不适合。



返回值的概念只存在于同步模型中。其中一个函数调用另一个函数,并且可以处理和返回值。但是你想要返回的值存在于函数回调中。这意味着整个执行线程将在回调函数之前执行,包括保存返回值的部分。



您需要异步思考。不要返回值,使用它们调用执行必要工作的其他函数。



我将尝试说明。让我们说我有代码:


  1. 执行某些操作

  2. 调用异步函数,

  3. $ b

    1-3在调用回调之前执行。这就是为什么它被称为回调!所以3将在我们有值之前执行。这没有意义。您需要更改代码以执行:


    1. 执行某些操作

    2. 使用回调函数调用异步函数使用一个值,并从上面执行3.


    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.

    解决方案

    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.

    这篇关于如何向main函数发送一个回调函数的回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆