'use strict';
const url = `https://www.exapmle.com/mediainfo?`
function getMediaInfo(videoid) {
fetch(url + videoid)
.then(response => {
if (response.ok === true) {
return response.text()
} else {
throw new error("HTTP status code" + response.status);
}
})
.then(text => {
const parser = new DOMParser();
const doc = parser.parseFromString(text, "text/xml");
console.log(doc) //I want to make 'doc' as getMediaInfo()'s return value
})
.catch(error => {
console.error(error)
});
}
答案 0 :(得分:1)
您需要返回承诺和承诺中的价值
function getMediaInfo(videoid) {
const url = 'https://www.exapmle.com/mediainfo?id='
return fetch(url + videoid)
.then(response => {
if (response.ok === true) {
return response.text()
} else {
throw new error("HTTP status code" + response.status);
}
})
.then(text => {
const parser = new DOMParser();
return parser.parseFromString(text, "text/xml");
})
.catch(error => {
console.error(error)
});
}
比调用函数
getMediaInfo(5).then(result => {
const doc = result
})
答案 1 :(得分:0)
另一种选择是使用异步/等待
"use strict"
const url = `https://www.exapmle.com/mediainfo?`;
async function getMediaInfo(videoid) {
try {
const response = await fetch(url + videoid);
if (response.ok) {
const text = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(text, "text/xml");
return doc;
} else {
throw new error("HTTP status code" + response.status);
}
} catch (error) {
console.error(error);
}
}
async function main(){
const doc = await getMediaInfo(5)
}