Mark
Mark

Reputation: 575

waiting for fetch results in javascript

I'm calling fetch a lot so I'm trying to make it a reusable function.

async function getXML(url) {
    const result = await fetch(url);
    const xml = await result.text().then(( str ) => {
        return new DOMParser().parseFromString(str, 'application/xml');
    });
    log(xml); //logs fine
}

I call it from var xml = getXML(url).then( work_with_setup_xml(xml) );

The function 'work_with_setup_xml' starts without data. How far off course am I?

Upvotes: 1

Views: 519

Answers (3)

Bergi
Bergi

Reputation: 665536

After fixing the return statement in getXML (as suggested in the other comments), your call is wrong. It should be either

getXML(url).then(work_with_setup_xml);

or

getXML(url).then(function(xml) { work_with_setup_xml(xml) });

or

var xml = await getXML(url);
work_with_setup_xml(xml);

Upvotes: 3

Gabor Szekely
Gabor Szekely

Reputation: 1238

This should do it:

async function getXML(url) {
  const result = await fetch(url);
  const str = await result.text();
  return new DOMParser().parseFromString(str, 'application/xml');
}

Upvotes: 2

Mike Doe
Mike Doe

Reputation: 17624

So how about returning the data for a change?

async function getXML(url) {
    const result = await fetch(url);

    return await result.text().then(( str ) => {
        return new DOMParser().parseFromString(str, 'application/xml');
    });
}

And actually using it:

let xml = getXML(url).then(xml => work_with_setup_xml(xml));

Upvotes: 0

Related Questions