'How to access a variable outside of an async function
I have an API call in the photoRetriever function. I saved the API object to the variable named "data" and I want to access this in the App class. I am trying to access an image in the API that is a method titled "url". It says that the variable data is not defined when I try to access it in the _generateMarkup method. What is the best way to define this variable so I can easily gain access to it outside of the function?
Code:
const photoRetriever = async function() {
try {
const res = await fetch('https://api.nasa.gov/planetary/apod?api_key=MHfiCXEcU8gFYbgux8MWX0nBFYRtzJsbefF4eq5R');
const data = await res.json();
console.log(data.url)
} catch(err) {
alert(err)
}
}
photoRetriever();
class App {
_parentEl = document.querySelector('.parent__el');
constructor() {
this._generateMarkup();
}
_generateMarkup() {
const markup = `
<div class="space__photo">
<img src="${data.url}" alt="" />
</div>
`;
this._parentEl.insertAdjacentHTML('afterbegin', markup);
}
}
const app = new App()
Solution 1:[1]
you have to return the value of the data into other variable with higher scope you can do something like this:
const photoRetriever = async function() {
try {
const res = await fetch('https://api.nasa.gov/planetary/apod?api_key=MHfiCXEcU8gFYbgux8MWX0nBFYRtzJsbefF4eq5R');
const data = await res.json();
console.log(data.url)
return data
} catch(err) {
alert(err)
}
}
class App {
_parentEl = document.querySelector('.parent__el');
constructor(data) {
this.data = data;
this._generateMarkup();
}
_generateMarkup() {
const markup = `
<div class="space__photo">
<img src="${this.data.url}" alt="" />
</div>
`;
this._parentEl.insertAdjacentHTML('afterbegin', markup);
}
}
async function main(){
const data = await photoRetriever();
const app = new App( data )
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ShobiDobi |
