Tips for invoking an asynchronous function within an if condition?

When trying to maintain variables in the background.js of a Chrome extension, I encountered difficulties that require me to reinitialize some global variables.

Here is the code snippet (view fiddle) I am using to demonstrate the issue:

var temp = null; 

function someTimeConsumingThing() {
  return new Promise(function(resolve,reject) {
    setTimeout(resolve, 2000);
    temp = 10;
  })
}

async function a(){
  if(temp==null){
    await someTimeConsumingThing();
  }
  return temp
}

function b(){
  let localTemp = a();
  console.log(localTemp);
}

b();

In the provided code, the temp variable may sometimes be null. To ensure it's not null, an async function someTimeConsumingThing needs to be called. However, the console output results in a Promise instead of 10. Adding await before calling function a() would lead to the error:

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules"

If you have insights on how to tackle this challenge, please share. Despite scanning various related responses without success, I am hopeful that experienced JavaScript experts might offer solutions here.

Answer №1

It appears that you missed using the await keyword when invoking the function a(), resulting in printing the returned promise instead of the asynchronous result of a(). Therefore, ensure that the containing function is labeled as async, since it features an await invocation.

Remember that it's recommended to designate the function someTimeConsumingThing as async because it gives back a Promise.

Furthermore, please note that your someTimeConsumingThing method initially assigns temp to 10 and then waits before returning. I've adjusted it so temp is set to 10 only after the delay has transpired.

let temp = null;

async function someTimeConsumingThing() {
  return new Promise(resolve => {
    setTimeout(()=>{
      temp = 10;
      resolve();
    }, 2000);
  })
}

async function a(){
  if(temp==null){
    await someTimeConsumingThing();
  }
  return temp;
}

async function b(){
  let localTemp = await a();
  console.log(localTemp);
}

b();

Answer №2

If a function calls another function that is asynchronous and requires the result of that function, then by definition it must also be asynchronous.

To convert b into an async function, you can do the following:

async function b(){
  let data = await fetchData();
  console.log(data);
}

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

Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the ...

Exploring html select and input elements in a loop

Currently, I am in the process of developing an application that calculates the total price of selected items based on user input. Each row consists of two dropdown menus (ID/item) and a quantity input field. Additionally, users have the option to add rows ...

Google Maps in Angular is not showing up

My Angular Google Maps implementation seems to be working, but unfortunately, the map is not showing on my website. I have confirmed that my JS is loading the maps and I can retrieve the map properties. Interestingly, when I check the Chrome AngularJS Debu ...

Having challenges retrieving information from MySQL in AngularJS

As a beginner in angularJS, I am trying to display all customers from MySQL. Here is the code I have written in the controller and service: app.controller('CustomersController', function ($scope, customersService, $http) { init(); function ini ...

Exploring the world of reactive programming in JavaScript by transforming traditional AJAX calls into Bacon.js streams while incorporating

How can I develop a method to convert calls to the server API to a Bacon.js / RxJs stream while supporting pagination? With pagination, I aim to keep track of the last requested item index and retrieve the next set of items based on the page size to popul ...

Verify whether a specific value is present within a nested array in MongoDB

Looking to verify whether a value sent in a request already exists within an array associated with a particular User. The data structure is as follows: { "_id": "63233972df0f14076e027106", "firstName": "mako" ...

What is the best way to extract the text from the first visible `<td></td>` table row using jQuery?

In this particular scenario, there is a table included: <table id="table"> <thead> <tr> <th>Name</th> <th>Course</th> </tr> </thead> <tbody> <tr style="display:none"> ...

Encountering an issue where rendering a component named Exercise within the ExerciseList component is not allowed

The ExerciseList component is designed to display all the exercises that can be edited or deleted from the list. It returns the Exercise Component or function for this purpose. If anyone could take a look and help identify any mistakes in my code, it would ...

Having trouble retrieving information from the local API in React-Native

Currently, I have a web application built using React and an API developed in Laravel. Now, I am planning to create a mobile app that will also utilize the same API. However, I'm encountering an issue where I cannot fetch data due to receiving the err ...

Backdrop behind of Bootstrap modal located back of other page contents

I'm facing some challenges after transferring a website I developed locally to a live server. The modal windows are appearing behind other content on the live server, although they work perfectly fine on the local version. Despite my attempts to adju ...

Paused momentarily to allow user input

I am currently developing a new game where the player and enemies are stored inside objects with various properties. For example, each object includes: $player->health $player->attack (which represents attack power) Additionally, there is a PHP fun ...

Setting a bookmark feature in HTML using localStorage: A step-by-step guide

I'm working on a simple code that captures the text content of a dynamically updated <h1> element and stores it as a "bookmark" in localStorage. I want to enable users to save or delete the bookmark by clicking a button. Below is a basic version ...

Vue transition not functioning properly when hovering over text for changes

When you hover over the circular region on the website, the text and description in the red box will change. To add a fade animation effect when the text changes, I attempted to use <transition> as per the documentation provided in this link. Unfor ...

Incorporating an offset with the I18nPluralPipe

Having trouble with my multiselect dropdown and the text pluralization. I attempted to use the I18nPluralPipe, but can't seem to set an offset of 1. ListItem = [Lion, Tiger, Cat, Fox] Select 1 Item(Tiger) = "Tiger", Select 3 Item(Tiger, Cat, Fox) = ...

Javascript: A Fun Game of Questions and Answers

When using JavaScript exclusively, I have an array consisting of four questions, four correct answers, and four incorrect answers. The use of arrays is essential to maintain order in the data. As each question is displayed, a random number is generated by ...

Customize the Color of Your Material-UI Drawer

Need help with setting the background color of a Material-UI Drawer. I tried using the following code but it didn't work: const styles = { paper: { background: "blue" } } After defining the styles, I passed them to the Drawer component like ...

Sharing JSON data between PHP and JavaScript/AJAX

In order to validate strings on my website, I am developing a validation mechanism using both Javascript and ajax for client-side validation and PHP for server-side validation. It is essential for both PHP and Javascript to utilize the same variables, suc ...

Error encountered: `unexpected token within ES6 map() function`

Do you see any issues with this code snippet? render(){ return ( var users= this.state.users.map(user => <li key={user.id}>{user.name}</li> ) <ul>{users}</ul> ) } I am receiving an error mes ...

Ways to extract link value in Angular

Is there a way to extract a value from a link using Angular 4? I have used *ngIf and would like to display a div based on the value within the link. <div *ngIf="obtain the value from the current href"> ...

I am unable to comprehend the function definition

I have familiarity with different types of JavaScript function declarations such as expression functions and anonymous functions. However, I am unsure about the syntax used in these two specific functions: "manipulateData: function (input)" and "getDataByI ...