Reputation: 575
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
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
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
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