Implementing async and await after making a fetch request

I am in the process of updating my code from using callbacks to utilize async and await. However, I am a bit confused on how to properly implement it within my current setup.

The current setup involves:

  1. Clicking a button that triggers the clicker function
  2. The clicker function then triggers the ajax function
  3. The ajax function performs a fetch request
  4. After receiving a response, I need to pass it back to the clicker function

Currently, I am receiving an undefined value from the ajax function. Can someone please assist me in identifying the issue?

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>

Answer №1

Experiment

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

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

var clickHandler = async function() {
  var result = await fetchData();
  console.log('clickHandler function', result);
};
.btn { border-radius: 5px; background: #00ff00; width: 80px; padding: 10px;cursor: pointer; }
<div class="btn" onclick="clickHandler(event, this);">
  Try It Out
</div>

Answer №2

Remember, you can only await a promise.

The reason the return value of ajax() is undefined is because there is no return statement included.

Although fetch does return a promise, it needs to be explicitly returned in order for it to be utilized.

To resolve this issue, make sure to include a proper return statement:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message retrieval in Liferay fails due to malfunctioning Ajax listener

While working on a project using liferay jsf, I encountered an issue with inserting <f:ajax listener="#{jsfController.searchValidDestination}"> within <h:selectOneMenu/> in my view page. The problem is that I am not getting any result from the ...

Are there any methods to utilize Zod for validating that a number contains a maximum of two decimal places?

How can I ensure that a numeric property in my object has only up to 2 decimal digits? For example: 1 // acceptable 1.1 // acceptable 1.11 // acceptable 1.111 // not acceptable Is there a method to achieve this? I checked Zod's documentation and sea ...

Capture various data points in an array with each click

I am currently working on a menu of buttons where users can select multiple options at the same time. My goal is to record all selected buttons in one array instead of individual arrays for each button. The end result I hope to achieve is an array like t ...

JavaScript: Unusual behavior discovered in forEach iteration

Here's the code snippet I'm having trouble with: someArray.forEach(x => { // do something console.log(‘calling api for ‘ + x); callAnHttpApiAsync(...); sleep(10); }); The issue lies in the asynchronous nature of the HTTP API call within ...

Struggling with a component that won't load in JSX?

Having some difficulty with React not rendering data associated with a component's props: import React from 'react'; import {ItemListing} from './ItemListing.js'; export var SearchResults = React.createClass({ render: functi ...

Tips for preventing window.location from becoming relative to the file

Despite my best efforts, I couldn't figure out why this issue was occurring or how to resolve it. Here is the code in question: window.location.href=("www.google.com"); The intended functionality of this code is to redirect to google.com, but inst ...

Using AJAX and React to handle RESTful requests

Hello there, I am attempting to utilize a web service in React but am encountering issues with the AJAX function. I'm unsure if my code is working as expected. Here is a snippet of my code: prox= {"email":email, "password": password}; //tag comment $ ...

Encountering module error 'internal/fs' after updating to Node 7

We have encountered some challenges after attempting to update our build server to node v7.0.0. Specifically, the application build task fails at the "bower_concat" step with the following error message: Loading "bower-concat.js" tasks...ERROR Error: Cann ...

Leverage the potential of the value parameter within a mongoose scope

I am currently trying to retrieve emails of a user based on their id. However, I have encountered an issue due to the asynchronous nature of the mongoose function. Mail.find({receiver_id: '#id#'}, function(err, mails) { var result = []; ...

Tips for linking server value with Javascript onmousedown in an aspx web page

I have a single Hyperlink on an aspx page. There are two tasks I need to accomplish: When I click on the hyperlink, I want to log some activity. While logging the EmployeeID value, I need to bind it from the server. However, I am encountering an error t ...

In Javascript, objects within local scope cannot be accessed from nested functions

I'm currently working on a function that is meant to retrieve an object from a PHP file located on a different page. I've implemented the jQuery ajax function to handle the JSON retrieval, and it seems to be functioning as intended. However, I&ap ...

Retrieving updated information from database (PHP)

I'm currently working on a piece of code that pulls data from my database. However, I'd like this data to automatically 'refresh' every 5 seconds so that any new entries meeting specific criteria will appear without needing to refresh t ...

Ways to reach state / methods outside of a React component

Implementing the strategy design pattern to dynamically change how mouse events are handled in a react component is my current task. Here's what my component looks like: class PathfindingVisualizer extends React.Component { constructor(props) { ...

What is the best way to retrieve data from this array?

Some of the code I have extracted from serialized data appears to not be in an array format. When attempting to use a foreach loop, it results in an error. array ( 'last_submit' => '1', 'feeds_changed' => '1', ...

methods for pausing music through a toggle button in a React JS application

I am facing an issue with the following shortcode for playing a song on a toggle button. The problem occurs when I try to pause the music and it does not stop as expected. import { React, useState } from 'react'; import './audio.css&apos ...

Leverage Angular to highlight updated items within a list

My goal is to synchronize data, so I have a data object that holds the current state. Whenever this state changes, I want to mark the object with an attribute for filtering purposes during syncing. Here is the structure of the object: data = { type1: [ ...

How can you include the product price in the cart using the URL on WooCommerce?

After some exploration, I discovered that I can easily add items to my cart using a specific URL: http://yoururl.com/cart/?add-to-cart=ID Although I was able to figure out how to include quantity and attributes in the link, I have not been able to determ ...

Steps to show a particular row in a Vue.js API

I have a question about how to retrieve data from an API and display it in a textbox when the edit button on a specific row table is clicked. The data should include its own id along with other details. I apologize for sharing my code in this format, as I ...

Having trouble making .click() function work in jQuery

Struggling with translating my javascript code to jQuery for homework. The .click function is causing me some serious issues. Here's a snippet of the code I'm working on: (document).ready(function() { $("start_test").click (function() { ...

bringing in a js file with an import statement at the beginning

I am looking to import a file that brings in another file for use across multiple pages Here is my folder structure: js modules momentum-scrolling index.js about.js contact.js Contents of momentum-scrolling.js: import LocomotiveScroll from &a ...