Mevia
Mevia

Reputation: 1564

async and await following fetch request

I am trying to rework my code that currently uses callbacks to use async, await. The only thing is that in my current setup i am a little bit confused about how it should be written.

The setup is that:

  1. i click a button that triggers clicker function
  2. clicker function triggers ajax function
  3. ajax function does fetch request
  4. after response is back I need to pass response to clicker function

Currently I am getting undefined from ajax function, could someone help and point out what is the problem?

var ajax = function() {
	fetch('https://jsonplaceholder.typicode.com/todos/1')
		.then(response => response.json())
		.then(json => { console.log('ajax function', json); return json; })
		.catch(error => console.log(error))
};

var clicker = async function() {
	var a = await ajax();
	console.log('clicker function', a);
};
<div onclick="clicker(event, this);">
	Test Me
</div>

Upvotes: 0

Views: 965

Answers (2)

Quentin
Quentin

Reputation: 943630

You can only await a promise.

The return value of ajax() is undefined because it has no return statement.

fetch returns a promise, but you don't return it.

Add a return statement:

return fetch('https://jsonplaceholder.typicode.com/todos/1')

Upvotes: 0

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92467

Try

var ajax = async function() {
  try {
    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
    let json = await response.json();
    console.log('ajax function', json)
    return json;

  } catch (error) {
    console.log(error)
  };
};

var clicker = async function() {
  var a = await ajax();
  console.log('clicker function', a);
};
.btn { border-radius: 5px; background: #00ff00; width: 80px; padding: 10px;cursor: pointer; }
<div class="btn" onclick="clicker(event, this);">
  Test Me
</div>

Upvotes: 2

Related Questions