I am using the same solution as this question. However, I want to load another JSON file after the when()
method. So in when()
I get a JSON data, then based on that, inside the then()
method, I want to load another JSON.
Here is my code:
var myJSON;
var myJSON2;
function _parseJSON() {
// return here, no need returning exactly what you would expect anyhow
return $.getJSON(settings.json_src);
}
function _parseJSON2(term) {
return $.getJSON("http://website.com/" + term ".json");
}
// because you returned, you can chain everything nicely together
$.when( _parseJSON() )
// don't forget the argument here
.then(function( data ) {
myJSON = data;
myJSON2 = _parseJSON2(data.value);
})
// and these will only run after the myJSON got set
.then( _cacheOptions )
.then( _cacheDom )
.then( _events )
.then( _render );
The line myJSON2 = _parseJSON2(data.value);
has to be ran when data
is loaded and myJSON2
must be saved as a variable to be used later in the code. It is more like another when().then()
is required.
Any idea how to make this working?
Thanks in advance.
Your $.when
is actually redundant but that isn't causing issues really
What you are missing with the _parseJSON2(data.value)
is to return it as a promise and simultaneously assign it's response to myJSON2
You could do something like:
function _parseJSON() {
return $.getJSON(settings.json_src)
}
/**
* Receives data from _parseJSON() and asssigns to myJSON variable
* Assigns new response to myJSON2
*/
function _parseJSON2(data) {
myJSON = data;
const term = myJSON.value
return $.getJSON("http://website.com/" + term ".json")
// this is the then() you were missing
.then(function(data){
myJSON2 = data;
// optionally return myJSON2 to next `then()`
});
}
// $.when not really needed
_parseJSON()
.then( _parseJSON2 )
.then( _cacheOptions )
.then( _cacheDom )
.then( _events )
.then( _render );
According to mozila.org
No need to use jQuery if you use fetch function
fetch("http://website.com/" + term ".json")
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.