简体   繁体   中英

Is there any other elegant way to fetch data from JSON and render it to DOM?

There is a simple JSON file named contents.json and I fetch this data in my localhost using this Pure JavaScript code,so my question is there any better way to do this kind of data fetching.

JavaScript

function fetchData(){
    fetch('http://localhost:5500/proje/contents.json').then(response => {
        return response.json();
    }).then(data => {
        console.log(data.Contents);
        const html = data.Contents
            .map(movie => {
                return `
                
                <div class="column">
                <img id="${movie.Title}"  src="${movie.Poster}" class="item img-2">
                <b class="text">${movie.Title}</b>
                </div>
                
                `
                
            }).join('');
        
        document.querySelector('#app').insertAdjacentHTML('afterbegin',html); 
        
    }).catch(error => {
        console.log(error);
    });

}

HTML

<div id="app"></div>

Image

图片

if you're talking about the method there is async await it will look like this

async function fetchingData(){
let data= await fetch('http://localhost:5500/proje/contents.json').json(),
html = data.Contents.map(movie => {
            return `
            
            <div class="column">
            <img id="${movie.Title}"  src="${movie.Poster}" class="item img-2">
            <b class="text">${movie.Title}</b>
            </div>
            
            `
            
        }).join('');)
document.querySelector('#app').insertAdjacentHTML('afterbegin',html); 
}

async tells the js engine that it will return a promise, but if you combine it with await, await makes JavaScript wait until that promise settles and returns its result. the function execution will pause on the line of await until the promise resolves, it is as simple as that.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM