0

How do I actually get data out of a Promise when using async/await? I've written an async function to gather some data that will be used later in the script. There are two fetch calls, with the second call being dependent upon the first. I understand that an async function will always return a promise, but I can't figure out how to get the data out of it.

I've tried both:

const my_async_function = async() => {
    try {
        const foo = await fetch(`api/foo/uuid`).then(res => res.json());
        const bar = await fetch(`api/bar/${foo.uuid}`).then(res => res.json());
        return bar.find(el => el.name === 'hello');
    }
    catch (err) {
        console.error(err);
    }
}
const data = my_async_function().then(res => res.json());

and

let data;
const my_async_function = async() => {
    try {
        const foo = await fetch(`api/foo/uuid`).then(res => res.json());
        const bar = await fetch(`api/bar/${foo.uuid}`).then(res => res.json());
        return bar.find(el => el.name === 'hello');
    }
    catch (err) {
        console.error(err);
    }
}
my_async_function().then(res => {
    data = res.json();
});

but neither works. The first version throws an error and in the second version data remains undefind. What am I missing?

Thanks in advance.

Tim
  • 103
  • 2

0 Answers0