И снова fetch promise в JS
Есть такой вот код:
const getData = () =>
fetch(apiUrl,{
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
redirect: "follow",
referrerPolicy: "no-referrer",
body: JSON.stringify(d),
}).then((response) =>
response.json()
);
const dataPromise = getData();
dataPromise.then((result) => {
console.log(result);
});
Нужно вытащить result "наружу". Как это сделать в "ванильном" JS?
Ответы (1 шт):
Автор решения: vlad visitor
→ Ссылка
let naruja = {};
//------------------------------
const xhr = new XMLHttpRequest();
xhr.open("POST", apiUrl, false);
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
naruja.response = JSON.parse(this.responseText);
}
}
xhr.send(JSON.stringify(d));
//------------------------------
console.log(naruja.response)
если без fetch, и если не критично использование синхронного запроса, то так работает