R
R
RandomProgrammer2021-07-26 13:14:19
AJAX
RandomProgrammer, 2021-07-26 13:14:19

How to make a function wait until another returns a result?

I am new to js. I have a code that receives comments from the server:

"use strict"

let request_count = 0;

let do_get_comment = true;

window.addEventListener("scroll", function(){
  if (do_get_comment){
              do_get_comment = get_comment()       [1]
        }
});


function get_comment(){
  let comment = new XMLHttpRequest();
  comment.open("GET", document.URL+"comments/"+request_count+"/");
  comment.send();
  let result;
  comment.onload = function(){
    if (comment.status == 200){
      set_comment(...);
      request_count++;
                        result =  true;
      }
    }
    else{
      result =  false;
    }
  }
        return result; [2]
}


I want that in the line [1] do_get_comment received the result of the get_comment call only after the onload is executed, i.e. line [2] is waiting for onload. I also read about callbacks, but I don't know how to apply them here.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2021-07-26
@RandomProgrammer

Example 1 - fetch, async/await

async function start() {
  const user = await getUser();
  
  console.log(user);
}

function getUser() {
  return fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(response => response.json());
}

start();
/*
{
  id: 1,
  name: 'Leanne Graham',
  username: 'Bret',
  email: '[email protected]',
  address: {
    street: 'Kulas Light',
    suite: 'Apt. 556',
    city: 'Gwenborough',
    zipcode: '92998-3874',
    geo: { lat: '-37.3159', lng: '81.1496' }
  },
  phone: '1-770-736-8031 x56442',
  website: 'hildegard.org',
  company: {
    name: 'Romaguera-Crona',
    catchPhrase: 'Multi-layered client-server neural-net',
    bs: 'harness real-time e-markets'
  }
}
*/

or
Example 2 - XHR, async/await
async function start() {
  const user = await getUser();
  
  console.log(user);
}

function getUser() {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    
    xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
    xhr.addEventListener('load', () => {
      if (xhr.status === 200) {
        resolve(JSON.parse(xhr.response));
      } else {
        reject(xhr.response);
      }
    });
    
    xhr.send();
  });
}

or
Example 3 - XHR, callback
function start() {
  getUser(user => {
    console.log(user);
  });
}

function getUser(callback) {
  const xhr = new XMLHttpRequest();

  xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
  xhr.addEventListener('load', () => {
    if (xhr.status === 200) {
      callback(JSON.parse(xhr.response));
    } else {
      callback(xhr.response);
    }
  });

  xhr.send();
}

start();

For the option with a callback function, two parameters are most often used: the first is an error, the second is the result, then the code will look like this:
Example 4 - XHR, callback with error handling
function start() {
  getUser((error, user) => {
    if (!error) {
      console.log(user);
    }
  });
}

function getUser(callback) {
  const xhr = new XMLHttpRequest();

  xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
  xhr.addEventListener('load', () => {
    if (xhr.status === 200) {
      callback(null, JSON.parse(xhr.response));
    } else {
      callback(new Error(xhr.response));
    }
  });

  xhr.send();
}

start();

Also, for XHR, you need to additionally handle errors.

R
Red_Devi1, 2021-07-26
@Red_Devi1

"use strict"

let requestCount = 0;

window.addEventListener('scroll', async () => {
  const result = await getComment();

  console.log(result);
});


function getComment() {
  return new Promise(((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `${document.URL}comments/${requestCount}/`);
    xhr.onload = function () {
      if (xhr.status === XMLHttpRequest.DONE) {
        set_comment(...);
        requestCount++;

        resolve(xhr.response);
      } else {
        reject(xhr.status);
      }
    };
    xhr.send();
  }));
}

Learn the Fetch API , it will make life easier

C
chaosmonk, 2021-07-26
@chaosmonk

https://developer.mozilla.org/en-US/docs/Web/API/X...
var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false); // `false` makes the request synchronous request. send
(null);
if (request.status === 200) {
console.log(request.responseText);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question