JS:变量返回undefined,但较早定义

时间:2020-04-12 21:35:43

标签: javascript asynchronous fetch-api

我的代码是

$chatID = $update["message"]["chat"]["id"];        
$keyboard=array("inline_keyboard"=>[[array("text"=>"nombre3","callback_data"=>"384937"),array("text"=>"nombrePrueba","callback_data"=>"394857"),array("text"=>"namePrueba2","callback_data"=>"938592"),array("text"=>"Google url","url"=>"http://google.com"),]]);
          $args = array(
              "chat_id" => $chatID,
              "text" => "Choose one:",
              "parse_mode" => "HTML",
              "reply_markup" => json_encode($keyboard),
          );

          $sendto =API_URL."sendmessage?".http_build_query($args);
          file_get_contents($sendto);

我用python 3的http.server启动了它,并打印了 $callback_query_id = $update['callback_query']['id']; $callback_query_from_id = $update['callback_query']['from']['id']; $callback_query_inline_message_id = $update['callback_query']['inline_message_id']; $keyboard=array("inline_keyboard"=>[[array("text"=>"Test","callback_data"=>"384937"),array("text"=>"Test2","callback_data"=>"394857"),array("text"=>"Test3","callback_data"=>"938592"),array("text"=>"Google url","url"=>"http://google.com"),]]); $args = array( "chat_id" => $callback_query_from_id, "text" => "Cool", "parse_mode" => "HTML", "reply_markup" => json_encode($keyboard), ); $sendto =API_URL."editMessageText?".http_build_query($args); file_get_contents($sendto); ,并且按预期提取失败。经过仔细检查,定义了变量myIP。我觉得这与异步和等待有关,但我不确定。

2 个答案:

答案 0 :(得分:0)

https://jsfiddle.net/Lyjkzqcf/

您可以通过geoloc()方法调用$.getJSON()。请在下面看看:

 var api_url
    
    $.getJSON("https://api.ipify.org/?format=json", function(e) {
        myIP = e.ip;
        geoloc();
        //api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
    });
    
    //api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
    
    async function geoloc() {
      api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
      console.log(api_url)
      const response = await fetch(api_url)
      const data = await response.json();
      console.log(data)
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

答案 1 :(得分:0)

尝试

async function geoloc() {
  api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
  console.log(api_url)
  const response = await fetch(api_url)
  const data = response.json();
  console.log(data)
}

仅将一次声明为asyncawait的功能。