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

To enhance your React Class Component, make sure to utilize the withStyles feature when

This particular component is not set as a default export component. I am attempting to apply some styles to it but struggling to figure out how to encapsulate it in an HOC. Hence, the current issue where it does not recognize the classes variable. import ...

Generating Speech from Text using jQuery API in HTML

Can a website be created to detect textbox text upon longClick by the user, and function across various browsers? The site should also have mobile compatibility. Appreciate any help! ...

Node: Await the completion of loading multiple images asynchronously

Despite seeing similar questions in the past, I'm struggling to solve my specific issue. My problem involves loading a batch of images before running another section of code. (async () => { const urls = <array of urls> await urls.map(url ...

@mui/x-date-pickers styling for the DatePicker component

Despite numerous attempts, I have been unsuccessful in styling the @mui/x-date-pickers <DatePicker/> component. I've experimented with various methods such as sx={{}}, style={{}}, makeStyles(), .css with the !important rule, renderInput={(param ...

What are the best practices for utilizing intro.js effectively on mobile devices?

Description When using introjs on mobile devices with a screen width of less than 600px, the tooltip ends up covering the element. When I hold the device horizontally, the tooltip adjusts its position accordingly. I attempted to apply custom CSS to the too ...

Having trouble with selecting checkboxes in a div using jQuery? While it may work in IE and Firefox, Chrome seems to be causing issues

In my div, I have several checkboxes placed under labels for formatting purposes. There is a list of checkbox names that need to be checked upon certain actions. Here is the list: var columns= ['2','5','4'] This is the curren ...

Trouble obtaining AJAX result using onClick event

As a newbie to AJAX, I am still trying to grasp the concept. My task involves using an AJAX call to extract specified information from an XML file. Even after carefully parsing all tag elements into my JavaScript code, I encounter a problem when attempting ...

Switch up the Angular base URL using ngx-translate

I successfully integrated ngx-translate into my Angular project. Now, I want to dynamically change the base href based on the language selected from the header menu. Currently, the URL appears as: "localhost:4200". However, upon launching the project, it ...

When using Webpack, there may be difficulties resolving relative path import of express static files

I am currently developing an Outlook add-in with an Express server running. To ensure compatibility with Outlook Desktop, I need to transpile JavaScript to ES5 using Webpack. Below is the simplified structure of my project: /public /javascripts ssoAu ...

jquery blur function not triggering properly

I am not very familiar with jquery and javascript. Below is the code I have written for an input text field where I want to use blur function for validation: <div class="form-row form-input-name-row"> <label> <span>Full name& ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Maintain a fixed element and enable the rest of the elements to scroll as the mobile browser address bar collapses while scrolling upwards

Currently facing a challenge where I want the background image to remain static while the address bar and content underneath scroll up. The image occupies 90% of the view height, and although I've prevented it from resizing and jumping when the addres ...

Fixed position not being maintained after clicking the button

Looking for some help with a fixed header issue on my website. The header is supposed to stay at the top while scrolling, which works well. However, when I switch to responsive view, click the menu button, and then go back to desktop view, none of the po ...

Creating or updating JSON files using Node.js

I am currently working with JSON files that contain an array of objects. I am looking to update one of these objects and subsequently update the JSON file by overwriting the old file. I understand that this cannot be achieved using AngularJS, but rather wi ...

Unable to delete touchmove event - Vue watching system

Preventing scrolling on mobile devices: const stopScroll = function(e) { e.preventDefault() } Adding the listener: document.body.addEventListener('touchmove', stopScroll, { passive: false }) Removing the listener: document.body.removeEvent ...

Why aren't variables showing up on the right when using writeFileSync in Node.js?

I'm attempting to insert a variable as ${Y} but instead of getting the actual data in Y, my output is showing (how can I write variable ${Y}). Does anyone have a solution for this? const fs = require('fs'); const Y = fs.readFileSync('./ ...

Instructions for including packages in .vue files

Within the script section of my .vue file, I have the following code: <script> import get from 'lodash.get'; ... </script> Despite trying to import lodash.get, I keep encountering an error message stating ReferenceError: ge ...

Angular and AngularJS directives work together to indicate events on a line chart

Currently, I am creating a dashboard using AngularJS along with Angularjs-nvd3-directives, mainly focusing on line charts. I am interested in adding markers to the chart for specific events. For instance, if I have a time series data, I want to be able to ...

In the world of programming, there exists a mysterious creature known as

I've been experimenting with different methods, but nothing seems to be working for me. What I am attempting to accomplish is <?php $php_var = a-thing; echo ' <script text/JavaScript> document.cookie = "arrayid"+&apos ...

Using an if statement within a map function in a React component

I am facing a challenge with using an if statement inside a map function without changing the return value. Here is my code snippet: this.example = this.state.data.map((item) => { return( <div> {if(1 + 1 == 2){ dat ...