javascript获取承诺及其返回值

时间:2020-09-10 23:49:10

标签: javascript promise fetch

'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)
        });

}

我想将值“ doc”作为getMediaInfo()的返回值。
但是我不知道该怎么做。有帮助吗?

2 个答案:

答案 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)
}