Reputation: 63
d3 is loading a Global array. I want to call that data in another function.
I don't understand promises very well and I can't decipher documentation.
First function called does:
d3.tsv( ... ).then(function(data){Loaded_Data[0]=data);}
Then a function is called to populate my svg:
svg.getElementById("example") = Loaded_Data[0][Loaded_Data[0].length-1]['Example Column']
I just can't figure out how to code: "Promise me that there is data in this Array, then do the value assignment"
Please be as explicit and obvious as possible. Thank you.
Upvotes: 1
Views: 165
Reputation: 2626
You can use the ES8 feature async/await
,
Let's imagine that you are executing your logic in a function called foo
,
// If you are using await inside a function it should be declared as async
async function foo(){
// await will make sure to pause the execution till the promise is resolved
Loaded_Data[0]=await d3.tsv( ... );
svg.getElementById("example") = Loaded_Data[0][Loaded_Data[0].length-1]['Example Column']
}
For more on async/await
, here is a great article,
https://alligator.io/js/async-functions/
Upvotes: 1
Reputation: 18805
If your 2 code snippets are in the same .js
file then you can likely just do:
d3.tsv( ... ).then(function(data){
Loaded_Data[0]=data;
svg.getElementById("example") = Loaded_Data[0][Loaded_Data[0].length-1]['Example Column'];
}
If this is not the case, then you could use an Observable, or you could trigger a custom Event that is called from within your .then
.
d3.tsv( ... ).then(function(data){
Loaded_Data[0]=data;
var event = new Event('Loaded_Data_HasData');
window.dispatchEvent(event);
}
and then in your other file / location, listen for that event.
elem.addEventListener('Loaded_Data_HasData', function (e) {
svg.getElementById("example") = Loaded_Data[0][Loaded_Data[0].length-1]['Example Column'];
}, false);
Upvotes: 1