1

I have some simple Promise in js:

 let link = "https://jsonplaceholder.typicode.com/posts/1";            
             
 fetch(link)
      .then(response => response.json())  
      .then(data => console.log(data))         
      .catch(error => console.error(error));

... and I want to translate it to 'async await' like here:

  const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1';

  const fetchUsers = async () => {
  const response = await fetch(API_ENDPOINT);
  const data = await response.json();  
  };

... but I don't know how involve it in 'async await' correctly. This involving gives error:

fetchUsers()
    .then(response => response.json())
    .then (data => console.log(data))
    .catch(error => console.error(`ERROR ${error}`));

Can you help me fix this error?

Jan Klimo
  • 4,643
  • 2
  • 36
  • 42

3 Answers3

0
 const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1';

  const fetchUsers = async () => {
    const response = await fetch(API_ENDPOINT);
    const data = await response.json();  
    console.log(data);
  };

Your code is working prefectly Just call fetchUsers() and It will print data through this line console.log(data);

You can't use await keyword outside the async type function

Read this -

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

Remember, the await keyword is only valid inside async functions. If you use it outside of an async function's body, you will get a SyntaxError.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
0

Async functions must be functions. So, you need to create a function to do that. MDN says:

The async function declaration defines an asynchronous function, which returns an AsyncFunction object.

Read more about that on MDN

So:

  1. Create a function using the async keyword
  2. Perform your fetch call inside the function using the await keyword
  3. Perform any other operations inside your function using the await keyword around any promise related operations (if you want)

An example below:

async function doFetch(link) {
    let result = await fetch(link); // this will wait the result to be fetched
    console.log(result); // this will only log the result of the fetch promise after it is resolved
    let json = await result.json();
    console.log(json);
}
const link = 'https://jsonplaceholder.typicode.com/posts/1';
doFetch(link);

Also, remember that when you use the await keyword, your asynchronous code will actually run synchronously, so, two sequential calls to any promises will run synchronously, like so:

async function foo() {
    let bar = await fetch('https://www.google.com');

    // the line below will run just _*AFTER*_ the above line is completely resolved
    let baz = await fetch('https://www.facebook.com');
}
0

Two problems here;

  1. You don't return anything from your async function
  2. You apply response.json() twice.

Just corect the code as;

const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1',
      fetchUsers   = async () => { var response = await fetch(API_ENDPOINT);
                                   return await response.json();
                                 };
fetchUsers().then (data => console.log(data))
            .catch(error => console.error(`ERROR ${error}`));
Redu
  • 25,060
  • 6
  • 56
  • 76