javascript 执行函数后做某事

javascript do something after executing a function

我已经看过很多post,但我仍然不明白回调。 我有这样的功能:

function getData (url) {
  request(url, function (error, response, data) {
      //...
      return data;
    }
  });
}

var data = getData(url);
// I got undefined because it's not finished
if (data) 
  ...

如何等待函数的 return 继续。我已经看到了很多关于回调和承诺的事情,但在这种情况下如何使用它呢? 例如我看过 this post 但我不明白答案。

我正在使用节点 js

getData 应将回调作为参数。

function getData(url, callback) {
    request(url, function (error, response, data) {
        callback(data);
    });
}

getData(url, function(data) {
    if (data) {
        ...
    }
});

首先,您需要了解调用 getData 的主线程即将结束,另一个将在 request[=17= 上打开] 函数,因此您需要在该新线程中继续。为此,您需要一个回调函数,即作为参数发送给 getData 函数的一段代码,可以在 request 时执行] 函数结束。你可以这样做:

function getData (url, callback) {
  request(url, function (error, response, data) {
      callback(data);
    }
  });
}

getData(url, function(data){
   // do something with the data returned
});

首先你有这样的问题是很自然的。

问题是您需要了解编程中的异步是什么,当您使用 'request' 函数时,您的代码将并行执行,因此您不必等待服务器响应。

您实际上需要在请求函数中使用您的 if(data) 。 像这样。

request(url,  function(error, response, data){
    //your if and your code after the response of this request need's to be placed here.
}

如果你想在服务器响应后处理请求,你应该这样做,但是这样当你的请求 returns 不是时,你总是有相同的代码?

所以你现在可以使用 'callback' 认为它是一个代表函数的变量。有点奇怪,但你及时得到。
好的,所以您将创建一个名为 'callback' 的变量来表示一个函数,但是!奇迹就在这里发生,如果您使用的是变量,则可以在编写代码之前进行更改。检查下面的示例。

function getData(url, callback){
 request(url, function(error, response, data){
   callback(error, response, data);
 }

//so when you use this function you can use another function in response like this.
getData('someUrl', function(error, response, data)
{
   //this piece of code will only be executed AFTER the request function returns.
});

我用谷歌搜索了一下,发现节点有一些同步调用,但如果你在节点中构建一个仅使用同步功能的系统,你应该更改你的服务器代码。