0

When dealing with async functions, I know that they always return a Promise. And to retrieve that value, I have to use .then or await. This is a function returning a Promise:

const getPeoplePromise = () => {
    return fetch('https://swapi.co/api/people')
        .then(res => res.json())
        .then(data => {
            return {
                count: data.count,
                results: data.results
            }
        });
};

The only way I know how to retrieve that date is like this:

    getPeoplePromise().then(data => {
        console.log(`Count data: ${data.count}`);
    })
};

But I want something like this (which should be possible, I just fail to nail the syntax I guess):
const i_want_this = getPeoplePromise().then().count; which returns undefined

Yes, I know there are several threads/questions on this topic already, but after searching for 30 minutes and going nuts, they all use the value in another function, which is fine and works for me too, I just cannot store the value right away. So this is different.

Leviathan
  • 644
  • 1
  • 15
  • 30
  • No, it's not possible, you can stop searching. – deceze Mar 24 '20 at 09:44
  • Well is there any way to store the result into a variable or will this always be a Promise? Like can I write a resolver function, which retrieves the value and stores that into the variable? – Leviathan Mar 24 '20 at 09:49
  • 1
    The problem is that the return value will be available ***sometime later.*** But `const i_want_this = ...` needs to resolve *now*. That's why you need to pass a *callback function* which will be called if and when the value becomes available (or paper over this with the `await` syntax). So, no, it's simply not possible. – deceze Mar 24 '20 at 09:50
  • What do you mean by paper over this? Sorry to bother you that much. Thank you for the the first explanation, that makes sense. – Leviathan Mar 24 '20 at 09:53
  • The `await` syntax simply turns `foo().then(bar => ...)` into `bar = await foo()`, but it ultimately still does the same thing, just slightly nicer. – deceze Mar 24 '20 at 09:54

0 Answers0