Reputation: 1564
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:
clicker
functionclicker
function triggers ajax
functionajax
function does fetch
requestclicker
functionCurrently 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
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
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