0

I'm beginning to understand async / await but I haven't figured it out yet. I really hope you can help me!

async function test1() {
  const fetchPromise = await fetch("https://www.instagram.com/boarirkeerd/?__a=1", {})
  .then(response => response.json())
  .then(response => {
    console.log(response["graphql"]['user']['id']); /* returns 43000480694 */
    return response["graphql"]['user']['id']; /* returns undefined */
  });};

if (await test1 == "43000480694") {console.log("YES");}
else {console.log('NO');} /* returns NO */
test1(); /* undefined */

The JS console shows: NO Promise 43000480694

Why is it in that order and why does the function return undefined? It should be: YES Promise 43000480694

Thanks a lot for your help!

Stefan Dacey
  • 165
  • 12
  • Because you return nothing from `test1`. You `return` from the promise callback, and the awaited value is then in `fetchPromise`. But you're not returning *that* from `test1`. – deceze Oct 21 '21 at 12:50
  • try changing `await test1` to `await test1()` – IWHKYB Oct 21 '21 at 12:50
  • You also shouldn't mix `await` and `then`: `const resp = await fetch(..); const val = await resp.json(); return val[..];`. – deceze Oct 21 '21 at 12:51

1 Answers1

0
  1. For a function to return something, it must at least have the return keyword.
  2. To reference a function, use test1, to call a function, use test1(). The () are required.
Evert
  • 93,428
  • 18
  • 118
  • 189