Asynchronous request and insertion of received nodes

16 hours ago 3
ARTICLE AD BOX
let el = (t, p = {}, ...c) => Object.assign(document.createElement(t), p, { append(...a) { return HTMLElement.prototype.append.apply(this, a), this; } } ).append(...c); const data = { // 🔸 Sending a POST request j(ms, ok = false) { return fetch(document.URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(ms) }) .then(async (response) => { const res = await response.json(); if (res.ms) { alert(res.ms); } else { ok?.(res); } }); }, // 🔸 Initialization int() { // creating a container this.element = el('div', { className: "header" }); // sending a request this.j( {news: id_news}, (response) => { // updating the DOM this.element.replaceChildren( ...response.map(item => el('div', { textContent: item[1] }) ) ); } ); } }; // запуск data.int();

First we create a container

this.element = el('div', { className: "header" });

Next, we send a request to receive an array, and insert the resulting array as nodes.

this.j( {news: id_news}, (response) => { // updating the DOM this.element.replaceChildren( ...response.map(item => el('div', { textContent: item[1] }) ) ); } );

Question, can we do this right away

this.element = el('div', { className: "header" }, ...this.j({news: id_news}));

As from the object

this.j()

get a response from the server?

The goal is to avoid creating variables like

this.element

As soon as we create an element, we add it to the house and when the response from the server arrives, we add child nodes. Without being bound to a variable...

Read Entire Article