-1

Mine is a simple button which make a xmlRequest Call to a json file in local server. its doing fine. but now i want to return a promise from inside the function

const button = document.getElementsByClassName('button')[2]
button.addEventListener('click', getJson)


function getJson() {
    this.xhr = new XMLHttpRequest()

    this.xhr.open("GET", "jsondata.json", true)

    this.xhr.onload = () => {

        return new Promise(
            (resolve, reject) => {
                console.log(this.xhr.responseText)
                resolve('this is success')
            }
        )

    }

    this.xhr.send()
}

but where do i catch the resolve and reject that the function getJson returns....I have tried passing the callback to the add event listener like

button.addEventListener('click', getJson(callback))

function callback(result) {
    console.log(result)
}

but the callback executes right away when the dom loads...i know its because of the parenthesis () i gave to getJson in the addEventListener...but i am falling in the same loop...so is there any way to add then functionality to the addEventListener because i want to get the Promise in return

Riyad Zaigirdar
  • 394
  • 1
  • 3
  • 10
  • Why not just call your callback method instead the Promise? – tomerpacific Jun 28 '20 at 09:27
  • Does this answer your question? [How do I promisify native XHR?](https://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr) – Marik Ishtar Jun 28 '20 at 09:28
  • Use fetch() that returns a Promise. XMLHttpRequest is outdated now. – Andy Jun 28 '20 at 09:34
  • Return a promise … to where? The `getJson` function is being called by the browser's event handling code, which isn't going to do anything with a promise that your code returns to it. – Quentin Jun 28 '20 at 10:28
  • instead of down-voting the provided solution, try reading them go through line-by-line. if you don't understand something just ask. – Kharel Jun 28 '20 at 10:38

2 Answers2

-1

How about?

document.getElementsByClassName('button')[2].onclick = function() {
    fetch('http://example.com/jsondata.json')
      .then(response => response.json())
      .then(data => console.log(data));
}

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Artur Kędzior
  • 3,557
  • 1
  • 30
  • 47
-1

const xhrBtn = document.querySelector("#xhr-btn");
const fetchBtn = document.querySelector("#fetch-btn");

const textarea = document.querySelector("#response");

// using fetch api
fetchBtn.addEventListener('click', async function() {
  this.disabled = true;
  textarea.textContent = "loading";
  textarea.disabled;

  const response = await fetch("https://reqres.in/api/users/1");
  //const payloadJSON = await response.json();

  textarea.textContent = await response.text()


  this.disabled = false;
  textarea.disabled = false;
});

// using XHR
xhrBtn.addEventListener('click', async function() {
  this.disabled = true;
  textarea.textContent = "loading";
  textarea.disabled;

  try {
    const xhr = await getJsonUsingXHR();
    textarea.textContent = xhr.responseText;
  } catch (error) {
    console.error(error);
  }

  this.disabled = false;
  textarea.disabled = false;
});

function getJsonUsingXHR() {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()

    xhr.open("GET", "https://reqres.in/api/users/1", true)

    xhr.onload = () => {
      if (xhr.status < 200 || xhr.status >= 300) {
        reject(xhr);
      } else {
        resolve(xhr);
      }
    };

    xhr.onerror = function() {
      reject(xhr);
    };

    xhr.send()
  });
}
body {
  display: flex;
  flex-direction: column;
}
<div>
  <button id="xhr-btn">Get JSON Using XHR</button>
  <button id="fetch-btn">Get JSON Using fetch API</button>
</div>

<textarea id="response" rows="12"></textarea>
Kharel
  • 779
  • 6
  • 15