簡體   English   中英

如何使這個 Javascript API 響應全局的 output ?

[英]How do I make the output of this Javascript API response global?

我正在嘗試接收 output 以獲取以下代碼,其中 cc 變量會將值記錄到空的全局國家變量中。 然后將其打印到控制台,但它不起作用。 我如何在這里使局部變量 cc 全局/給全局變量 country 一個值?

 var country = ''; fetch('https://extreme-ip-lookup.com/json/').then( res => res.json()).then(response => { var cc = (response.countryCode); country = cc; }); console.log(country);

您的問題似乎與代碼的異步性質有關。 讓我解釋。

var country = '';
fetch('https://extreme-ip-lookup.com/json/')
    .then( res => res.json())
    .then(response => {
        var cc = (response.countryCode);
        country = cc;
    });
console.log(country);

獲取 function 是異步的。 這就是您需要.then方法的原因。 這意味着當 fetch function 運行時,JavaScript 不會停止程序的 rest,而是在fetch()在后台運行時繼續。 因此,當您console.log(country)時,它仍然是原始值(空字符串)。

要回答您的問題,您可以使用Promise記錄 cc 的值。

var country = '';
const fetchPromise = fetch('https://extreme-ip-lookup.com/json/')
    .then( res => res.json())
    .then(response => {
        var cc = (response.countryCode);
        country = cc;
    });

Promise.resolve(fetchPromise) // Waits for fetchPromise to get its value
    .then(() => console.log(country))

您可以在MDN 文檔中找到有關 Promise 的更多信息

您當前調用console.log(country)country設置為response.countryCode之前的問題。

您可以通過以下方式將代碼放入異步IIFE中來解決此問題:

 (async () => { const response = await fetch('https://extreme-ip-lookup.com/json/'); const ipData = await response.json(); const country = ipData.countryCode; // place all code that uses `country` in here console.log(country); })();


如果您有另一個腳本,其中 function 定義取決於county ,請務必接受它作為參數,不要從全局變量中提取數據。

// helper_functions.js

// Bad
function someFunctionThatUsesCountry() {
  console.log(country); // <- don't expect the global to be set
}

// Good
function someFunctionThatUsesCountry(country) {
  console.log(country); // pull country ^ from the parameter list
}

然后,您可以通過傳遞值來調用 IIFE 中的其他腳本。

(async () => {
  // ...
  someFunctionThatUsesCountry(country);
})();

如果出於某種原因想要一個全局變量真的很糟糕。 您應該將 promise 放在此變量中,而不是值中。 使用此 promise 您可以傳遞該值,並在該值可用時通知其他腳本。

// script_1.js
window.country = fetch('https://extreme-ip-lookup.com/json/')
                 .then(response => response.json())
                 .then(ipData => ipData.countryCode);
// script_2.js (must be loaded after script_1.js)
window.country.then(country => { // <- wait until country is available
  // do stuff with country
  console.log(country);
});

您的問題來自這樣一個事實,即您的 fetch 是異步 function,帶有 promise。

你想做的是(我想)

var country = '';
//then
fetch('https://extreme-ip-lookup.com/json/')
.then( res => res.json())
.then(response => {
    var cc = (response.countryCode);
    country = cc;
 });
//then
console.log(country);

但是,由於您使用異步 function,因此可以這樣做:

//first
var country = '';
//second
fetch('https://extreme-ip-lookup.com/json/')
.then( res => res.json())
.then(response => {
    //fourth
    var cc = (response.countryCode);
    country = cc;
 });
//third
console.log(country);

如何解決? 看情況。 如果您的console.log 是由按鈕觸發的,請等待填寫國家/地區

否則,將您的代碼放在最后,或使用Promise.all()此處的文檔)

console.logfetch解決之前發生。 嘗試這個:

let country = '';
fetch('https://extreme-ip-lookup.com/json/')
    .then(res => res.json())
    .then(res => country = res.countryCode)
    .then(() => console.log(country))
  

fetch返回一個Promise ,因此是您問題中的 .then .then()鏈。

但是如果你踏入Promise Land,你就不會發現了。 你必須用 Promises 做所有事情。

但是您可能會將您的邏輯拆分為可管理的小部分,例如這里

 console.clear() let cached = null; const lookup = () => fetch('https://extreme-ip-lookup.com/json/'); // Caching json and not the fetch promise, because // https://stackoverflow.com/a/54731385/476951 const getJson = () => cached = cached || lookup().then(response => response.json()); const getParameter = (parameter) => getJson().then(json => json[parameter]); const getCountry = () => getParameter('country').then(value => value); const getCountryCode = () => getParameter('countryCode').then(value => value); getCountryCode().then(countryCode => { console.log('countryCode:', countryCode) }) getCountry().then(country => { console.log('country:', country) }) getParameter('city').then(city => { console.log('city:', city) })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM