有没有一种方法调用返回的父函数从JavaScript的一个子功能?个子、函数、功能、方法

2023-09-10 21:44:22 作者:久故

我有一个很特殊的情况。我想返回一些数据 - 即通过AJAX下载的数据。到目前为止,异步和放大器;同步模式没有得到数据的时间到返回。是否有可能,我可以或者调用返回从子函数父功能或可能超时解决这一问题?我想不出这样做的另一种方式,但必须将数据返回。

I am having a really peculiar case. I want to return some data - data that is downloaded via ajax. So far async & sync modes don't get the data in time to the return. Is it possible I could either call return from a child function for the parent function or could a timeOut solve the issue? I can't think of another way of doing this, but the data must be returned.

推荐答案

在回答你的问题是没有。

The answer to your question is no.

在异步请求,该函数返回的结果可用之前。要解决这个问题,一个回调模式用于 - 调用这样一个函数时,你不要指望回报,而是为它提供一个回调 - 一个函数被调用一次的结果是可

In asynchronous requests, the function has to return before the result is available. To work around this, a callback pattern is used - when calling such a function, you don't expect a return, but rather provide it with a callback - a function to be called once the result is available.

下面是一个简单的例子:

Here's a simple example:

var someValue;
fetchValueFrom('http://example.com/some/url/with/value', function(val) { 
  someValue = val; 
  doSomethingElseWith(someValue);
});

下面我们创建了一个功能,在把它作为第二个参数的 fetchValueFrom 通话。当值可用此功能将被调用,并设置变量并调用另一个函数继续执行。

Here we create a function and pass it in as a second param to the fetchValueFrom call. Once the value is available this function will be called, and will set the variable and call another function to continue execution.