0

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?

Mark
  • 555
  • 6
  • 17

3 Answers3

2

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');
}
Gabor Szekely
  • 1,108
  • 5
  • 14
2

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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

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));
Mike Doe
  • 16,349
  • 11
  • 65
  • 88
  • [Avoid `return await`](https://stackoverflow.com/q/43353087/1048572), or even in general [mixing `await` with `.then(…)` syntax](https://stackoverflow.com/a/54387912/1048572). – Bergi Feb 13 '19 at 20:00