Search code examples
javascriptes6-promise

Returning value of promise is diffrent when I use it outside function and cant really get why


I have 2 js files. I'm trying to call in index.js result of a promise from function all() in listings.js. And it logs expected object with data as result if I console.log inside async function all(), all is good BUT once I try return value to index.js and store it in variable and then console this variable it shows that inside of it some promise with status panding... What? Is there is something I don't know? Once again I wrapped it into await to get result and it's what I expected inside that function, but once I return value from func it looses into promise. Question: how do I properly return value to variable?

index.js

import 'babel-polyfill';
import {all} from './listings';

let result = all();
console.log(result); //returns promise, why???

listings.js

export async function all() {
    let res = await makeRequest('http://sellbuyschool42.com/listings');
    console.log(res); //return expected object with data, all is GOOD
    return res;
}

function makeRequest($url, options= {})
{
    return fetch($url).then((responce) => {
        if(responce.status != 200)
        {
            return responce.text().then((text) => {
                throw new Error(text);
            })
        }
        return responce.json();
    })
}

Solution

  • Remember that an async function returns a promise. It does not return the result of that promise. Instead, you must resolve that promise to get the value.

    In your index.js file, when you call the all() function you need to either use then() or await to get the actual result of the async function.

    let result = await all();
    console.log(result);
    

    OR

    all().then((result) => {
        console.log(result);
    }
    

    Remember that in the first solution (if you use await), you'll need to make that parent function async as well.