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

}

I want to make value 'doc' as getMediaInfo()'s return value.
But I don't know how to do it. Any help?
kipp
  • 3
  • 2
  • 1
    You need to return the fetch value and return the doc variable in your then block. – Phix Sep 10 '20 at 23:55

2 Answers2

1

You need to return the promise and the value from the 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)
        });

}

Than call the function

getMediaInfo(5).then(result => {
  const doc = result
})
Bergur
  • 3,962
  • 12
  • 20
  • 1
    oh you should fix this ``` getMediaInfo(5).then(result => { const doc = result } ``` to ``` getMediaInfo(5).then(result => { const doc = result }) ``` – kipp Sep 11 '20 at 01:26
1

Another option is to use async/await

"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)
}
david snyder
  • 337
  • 3
  • 16