Requires a clearer understanding of asynchronous functions

I am attempting to retrieve the value from a setTimeout function, but I am not seeing any output in the console. How do I properly handle asynchronous functions like this? Can someone explain the correct approach to me?

This is what I have tried:

async function getTheme() {
        const value = 'abc'
        setTimeout(() => {
            return value;
        }, 3000);
    }
    
    getTheme().then(result => console.log(result)); //not receiving any output.
    

Answer №1

The reason for this issue is that the return statement is inside the setTimeout callback, which does not actually resolve the promise.

To fix this, you should return a promise instead:

function getTheme() {
    const value = 'abc'

    return new Promise(resolve => {
        setTimeout(() => resolve(value), 3000);
    })
}

It's unnecessary to use async in this case since you are already returning a promise within the getTheme() function.

If you prefer, you can encapsulate the waiting logic into another function and still use async:

function sleep(duration) {
    return new Promise(resolve => setTimeout(resolve, duration));
}

async function getTheme() {
    const value = 'abc';

    await sleep(3000);

    return value;
}

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

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

Stop the recurrence of multiple clicks by incorporating a Bootstrap modal popup confirmation

$('button[name="remove_levels"]').on('click', function (e) { var $form = $(this).closest('form'); e.preventDefault(); $('#confirm').modal({ backdrop: 'static', ...

Different ways to implement the Vue search select feature in various form structures

I am facing an issue with showing select options of my product in multiple forms. Whenever I choose one option in one form, all the other select forms also change automatically. How can I make each select form unique? Here is what I have tried: My selec ...

What is the process for having a Google Map marker direct to a specific URL?

Check out my HTML: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <style> /* Customize the dimensions of the div element that houses the map */ #map { height: 700px; /* K ...

Populate DataTable with HTML content by fetching it through Ajax requests

My goal is to dynamically load the HTML returned from a controller into a div when a user clicks on a row in a table. Check out my code snippet below: // Add event listener for opening and closing details jQuery('#exRowTable tbody').on ...

Getting data from JSON to fill an array: A step-by-step guide

I am currently facing an issue where I am trying to incorporate data from a JSON file into my array, but for some reason, the information is returning as 'undefined' because nothing is being created in my array. Below are the contents of the JSON ...

What is the best way to retrieve information from an http website and display it in an html table using javascript

I am attempting to retrieve data from the specified site: . The website appears to feature a list of objects, and my goal is to extract each object enclosed in {} into separate columns within a row (6 columns total - one for gameNumber, one for teams, and ...

Dynamically assigning a name to a variable through code

Is there a quicker way to complete these 100 tasks? variable_1 = 1; variable_2 = 2; variable_3 = 3; ... variable_100 = 100; I attempted to use the following code: for(var i = 1; i <= 100; i++) { variable_ + i = i; } However, I encountered an e ...

Challenges with enigmatic ajax json requests in jQuery

I am trying to retrieve an rss feed in json format using a Google API with my jQuery code. I have added some alerts, but they do not seem to be displaying when I run the page. What could be causing this issue? Here is the snippet of my jQuery code: funct ...

Creating a specific ng-init condition for introducing new elements into the scope

Using ng-repeat, I am generating a series of todo items within div elements. My goal is to automatically apply the "editing = true" styling to these newly created items and if possible, focus on them as well. <div class="item" ng-class="{'editing- ...

"Unsuccessful jSON request made by Ajax resulting in undefined response

I've implemented an ajax call to fetch data from a json file and display it in an HTML table. Everything was working fine initially, but now it seems to be returning UNDEFINED. Could it be that the data from the json file hasn't finished loading ...

Automatic closure of the div tag in JavaScript

I am revamping my website to a more modern web application, and here is the HTML code I am using: <joexn-profile> <joexn-logo></joexn-logo> <joexn-text></joexn-text> </joexn-profile> Additionally, here is the JavaScrip ...

Clicking on Vue ChatJS to instantly redirect

Utilizing the Vue ChartJS, I have successfully generated a Line Chart. My Objective: I want to redirect the user whenever they click on a data point. Here is a screenshot for referencehttps://i.sstatic.net/06kWB.png For instance, clicking on the first ...

Producing asynchronous JavaScript events using a browser extension (NPAPI)

Currently in the process of developing a web browser plugin using NPAPI. The issue I am facing is that my plugin requires a worker thread to handle certain tasks, and I need to pass events back to JavaScript as the worker progresses. However, due to the N ...

Manage the dimensions of elements using Javascript on the client side

Here is a form I created: <form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp"> <input type="file" name="pho" id="photo" class="inph" accept="image/*"> <button type="submit" id=" ...

Check to see if a div element with an id that contains a numerical value has been

My HTML code contains X elements, each with an ID in the format: viewer_mX In this case, X is a number ranging from 1 to m (where m varies). I am looking to utilize JavaScript to retrieve the respective element's number X when a user clicks on one ...

Clicking a link using Selenium WebDriver and JavaScript

I am currently utilizing Selenium-webdriver with C# to run tests on a website. However, I am encountering an issue where the Click() function is not working when I try to click on a link. The expected behavior is for a new window to open upon clicking the ...

Error in sorting the table within an expandable table feature in CodeIgniter

I've been working on a way to make my table data sortable within an expandable table view. I attempted using the code provided in the link below: Code Link My current view looks like the image shown below. However, after implementing the code on my ...

What is the reason behind $(this).text() returning an empty string when clicking on an li element?

Can anyone explain why clicking on this element returns a blank string ""? function saveSelection() { var selectedValue = $(this).text(); // The value here is "" } This pertains to: <ul> <li data-bind="item" onclick="saveSelection();"> ...

Updating a function in jQuery UI after dynamically loading content through AJAX

I've been on a quest for days now, searching high and low for an answer to my dilemma. While I've managed to solve most of the issues that arose after adding AJAX calls to my code, there's one piece that still eludes me. Just to provide som ...