【问题标题】:javascript fetch promise and its return value [duplicate]javascript获取承诺及其返回值[重复]
【发布时间】:2020-09-11 09:29:43
【问题描述】:
'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() 的返回值。
但我不知道该怎么做。有什么帮助吗?

【问题讨论】:

  • 您需要返回 fetch 值并在 then 块中返回 doc 变量。

标签: javascript promise fetch


【解决方案1】:

你需要返回promise和promise中的值

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

【讨论】:

  • 哦,你应该修复这个 ``` getMediaInfo(5).then(result => { const doc = result } ``` 到 `` getMediaInfo(5).then(result => { const doc = 结果}) ```
【解决方案2】:

另一种选择是使用异步/等待

"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)
}

【讨论】:

    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 2015-02-13
    • 2019-11-02
    • 2014-05-21
    • 2019-01-23
    • 2018-12-24
    • 2020-08-26
    相关资源
    最近更新 更多