XMLHttpRequest async problems (I believe so)

Hi I’ve been doing some projects from Hackajob and I’ve just struggled a whole day because of this issue.

The project I had to accomplish (I couldn’t make in time) is about JSON and async functions and I think i didn’t understand well how to deal with this.

So I had to get JSON data from API .
I could do this when I am fetching data from one endpoint but when I’m doing it from another endpoint It didn’t catch data from one side

so this is my cod

var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest
let request = new XMLHttpRequest()
const filmAPI = 'https://challenges.hackajob.co/swapi/api/films/?search='
const charAPI = 'https://challenges.hackajob.co/swapi/api/people/?search='

function run (film, character) {
  reqFunc(film, filmAPI) + reqFunc(character, charAPI)
}
const reqFunc = (input, API) => {
  let data
  var promise = new Promise((resolve, reject) => {
    request.open('GET', API + input)
    request.send()
    request.onload = () => {
      if (request.status === 200) {
        // console.log(API)
        if (API == filmAPI) {
          data = JSON.parse(request.responseText).results[0].characters
        } else if (API == charAPI) {
          data = JSON.parse(request.responseText).results[0].films
        }
        resolve(data)
      } else {
        reject(Error(request.statusText))
      }
    }
  })

  promise.then(data => {
    // console.log(data)
    let charList = []
    for (let i = 0; i < data.length; i++) {
      let charReq = new XMLHttpRequest()
      charReq.open('GET', data[i])
      charReq.send()

      charReq.onload = () => {
        if (API == filmAPI) {
          charList.push(JSON.parse(charReq.responseText).name)
        } else if (API == charAPI) {
          charList.push(JSON.parse(charReq.responseText).title)
        }
        if (i == data.length - 1) {
          return console.log(input + ':' + charList.sort().join(', ') + ';')
        }
      }
 
    }
  })
}

run('A New Hope', 'Poggle the Lesser')

When I run run fuction(I know the name is a bit confusing lol sorry for this) it has to have an return value of
“A New Hope: Beru Whitesun lars, Biggs Darklighter, C-3PO, Chewbacca, Darth Vader, Greedo, Han Solo, Jabba Desilijic Tiure, Jek Tono Porkins, Leia Organa, Luke Skywalker, Obi-Wan Kenobi, Owen Lars, R2-D2, R5-D4, Raymus Antilles, Wedge Antilles, Wilhuff Tarkin;Poggle the Lesser:Attack of the Clones, Revenge of the Sith;”
something like this. but I only got

“Poggle the Lesser:Attack of the Clones, Revenge of the Sith;”

I think I’m just finding a right way to handle double async function.
When I run reqFunc seperately it works as I intend.
I’ve searched articles and followed the tutorials but I couldn’t get it yet.

It would be really thankful if anyone can give me a hint of this!

Thank you campers and Happy coding! :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.