Search code examples
javascriptfetch-api

Javascript returned data from function which fetches an api


I have the follwoing function which uses fetch to cal a restfull APi and get the output data which is in text format:

async function fetchText(url) {
            let response = await fetch(url);
            let data = await response.text();
            console.log('data...',data);
            return data;
        }

The function execution of this script

mydata=fetchText(myurl);
console.log("mydata...........",mydata);

returns this out put

mydata........... Promise[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: ""6269A297-851B-4158-873B-66F068B73BCD"" data... "6269A297-851B-4158-873B-66F068B73BCD"

How to change the function so that its output is exactly what is displayed by the log instead of the Promise type ?


Solution

  • function that uses async keyword will always returns promise, so use following code to print value.

    fetchText(myurl).then(data=>{ console.log(data) })