简体   繁体   中英

Return object from async function

I've tried several ways to return an object from an async function. I'm quite new to JavaScript, and I can't see why this does not work.

The function uses an API to return some financial data, then after it gets the response it maps the returned Object into another object, which I want to return.

If I console.log the object, everything is ok. But having a lot of numbers in my terminal is not really what I hope to achieve.

I've tried the following:

let someObject = fetchData(url);
console.log(someObject)

Gives me "Promise { }"


Another try:

const returnFetchData = async() => {
    const objectToReturn = await fetchData(url);
    return objectToReturn;
}


console.log(returnFetchData);

Gives me "[AsyncFunction: returnFetchData]"

Heres my code:

async function fetchData(urlLink){
const res = await fetch(urlLink);
const out = await res.json();
const timeSeries = out['Time Series (Daily)'];

let returnObject = {
    dates: [],
    adjustedClose: []
}


Object.entries(timeSeries).forEach(
    ([key, value]) => {
    returnObject.dates.push(key)
    returnObject.adjustedClose.push(value['5. adjusted close'])
    }
);


return returnObject;

}

Edit: I want to return the array from returnObjects.adjustedClose.

All solutions so far returns a promise. This array should be used in another function, should I therefor map it in that function?

In your code

const returnFetchData = async() => {
    const objectToReturn = await fetchData(url);
    return objectToReturn;
}

console.log(returnFetchData); 

Swap out the console.log(returnFetchData); with console.log(await returnFetchData());

You must await an async function .

You can not return the data as it's not ready immediately. The data you want to return depends on some requests, so it needs some time to be prepared. To sum up you have to await that function, fetchData, to fetch and prepare data, then it will be ready to return the data you want.

Consequently, you can reach the array you desire, returnObject.adjustedClose, by blocking like this:

let desiredData = await fetchData(urlLink);
let desiredArray = desiredData.adjustedClose;
console.log(desiredArray);

or non-blocking like this:

fetchData(urlLink).then((desiredData) => {
  let desiredArray = desiredData.adjustedClose;
  console.log(desiredArray);
});

Keep in mind that these both will not log the desiredData immediately, it will take some time to fetch data from the urlLink and to prepare it.

State one option of these lines of code, wait some seconds and see the result in the console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM