代码以错误的顺序执行

hol*_*ard 2 javascript ajax jquery json function

我知道Javascript是异步的,但在这种情况下我无法理解为什么会发生这种情况.

在下面的第27行,我调用函数'GetProducer',该函数应该返回我后来要使用的特定生产者的数据.但是,当安慰它时,它会被取消定义,这是因为第28行的代码在检索数据之前执行(第27行).

为什么会发生这种情况,我该怎么做才能解决它?

1.     function GetProducer(id) {
2.  
3.          $.ajaxSetup ({
4.            url: "http://localhost/api/v1/producers/" + id,
5.            type: "GET",
6.            dataType: "json",
7.            cache: false,
8.            contentType: "application/json"
9.          })
10.         $.ajax({
11.             success: function(data){
12.                 return data;
13.             },
14.             error: function(xmlHttpRequest, textStatus, errorThrown) {
15.                 console.log(xmlHttpRequest);
16.                 console.log(textStatus);
17.                 console.log(errorThrown);
18.            }
19.         }).done(function(data){
20.             console.log(data);
21.         })
22.      }
23.
24.     $('.modal-btn').click(function(){
25.         var producerId = $(this).attr('id');
26.         $('#myModalLabel').html(producerId);
27.         var info = GetProducer(producerId);
28.         console.log(info); // <--- undefined
29.     });
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 5

一个returnajax的回调函数内的语句是没用的.该函数是异步调用的,您不能指望任何东西将返回的值传递给任何东西.

如果您将console.log()呼叫置于 "成功"回调中,您将看到一个值.

您可能需要更改"GetProducer"函数,以便它也需要一个回调参数:

    GetProducer(producerId, function(info) { ... });
Run Code Online (Sandbox Code Playgroud)

然后,函数或多或少看起来像这样:

  function GetProducer(producerId, callback) {
    $.ajaxSetup({
      // ... same
    });
    $.ajax({
      success: function(data) {
        callback(data);
      },
      // etc
    });
  }
Run Code Online (Sandbox Code Playgroud)

因此,回调函数将放置处理"生产者"信息的代码.异步编程就是在结果可用时提供处理结果的API函数.

  • @AlexeiLevenkov肯定是.我认为OP可能希望在他跑步之前走路,但是也许对于初学者而言,延迟功能更容易理解! (2认同)