Is it possible to set a variable to a specific value inside a callback function in JavaScript?

Currently, I'm working on developing a Chrome extension that focuses on conversions. However, I've hit a roadblock when it comes to retrieving data from storage. Below is the code snippet I'm currently using:

var conversionFactor = 1;
        chrome.storage.sync.get("conversion", function(fetched) {
            var tempCon = fetched.conversion;
            if(tempCon.includes('toKG')) {
                conversionFactor = 0.45;
            } 
            else {
                conversionFactor = 2.2;
            }
        });
    alert(conversionFactor);

Despite my efforts, the alert always displays a value of 1. Is it not supposed to update the value before the alert is triggered? Additionally, I'm curious if there's a way to extract a value from chrome.storage and use it outside of the callback function within the chrome.storage.sync.get statement.

Answer №1

chrome.storage.sync.get is a function that works asynchronously. To retrieve the correct value, it is important to move the alert inside the callback function.

chrome.storage.sync.get("conversion", function(fetched) {
    var tempCon = fetched.conversion,
        conversionFactor;
    if(tempCon.includes('toKG')) {
        conversionFactor = 0.45;
    } 
    else {
        conversionFactor = 2.2;
    }
    console.log(conversionFactor);
});

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

Data-api configuration for bootgrid ajax

According to the BootGrid documentation, in order to set the HTTP method to GET or enable AJAX, one must use the method and ajax attributes in JavaScript. However, the Data-API example demonstrates the use of data-url and data-ajax, leading me to conclude ...

Using discord.js does not allow line breaks in embed descriptions

const chatRoom = replyOptions.getRoom("room"); const header = replyOptions.getHeader("header"); const content = replyOptions.getContent("text"); const chatEmbed = new MessageEmbed() .setColor('DARK_VIVID_PURPLE') ...

"Launching a node server in Azure to get you up and running

Currently, I have a Single Page Application that is hosted on Microsoft Azure. This application requires refreshing some dashboard data every 5 seconds. To achieve this, I have developed a nodejs service that continuously requests data from the API and gen ...

Leveraging ngIf and ngFor within choice

Is there a way to combine ngIf and ngFor in a single line of code? Here is the code snippet I am currently using: <option *ngIf="tmpLanguage.id!=languages.id" *ngFor="let tmpLanguage of languages" [ngValue]="tmpLanguage.id"> {{tmpLang ...

Leverage the retrieved configuration within the forRoot function

Currently working on an Angular app that uses @ngx-translate. In my implementation, I am using TranslateModule.forRoot(...) to set up a TranslateLoader: @NgModule({ imports: [ TranslateModule.forRoot({ loader: { provide: TranslateLoade ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

The CSS and Bundle script path may need adjustment following the creation of the index.html file by WebPack

There seems to be an issue with webpack trying to add 'client' to the href of script tags for my CSS and bundle files. This is causing a problem as it's incorrect and I'm unsure how to remove it. Prior to switching to webpack, here&apo ...

Preparing data before using Kendo UI upload function is essential

I need to pass a data (specifically a GUID) to the upload method of the kendoUpload, so that a particular MVC Controller action method can receive this data each time the upload occurs. $("#propertyAttachmentUpload").kendoUpload({ async: { ...

Creating a secure authentication system with Parse for password recovery and website logins

Our organization has chosen to utilize a Parse backend for managing user accounts, and I am tasked with creating web pages for functionalities like password reset that will seamlessly integrate with our mobile applications. It has been some time since I ha ...

Identify and emphasize fields that contain identical, non-empty values

I am attempting to compare the values of textboxes and highlight them if they are the same, excluding any textboxes that are empty. Feel free to view an example on this JSFiddle link: http://jsfiddle.net/qjqa1et2/61/ Below is the jQuery code I am current ...

Refusing to include two values due to the presence of a comma in JavaScript

I'm trying to add two values with commas and .00 (Example: 1,200.23 + 2,500.44) but it's not working because the textbox includes commas as required by my system. The result shows NaN because the comma is considered a special character. It was w ...

Creating a dedicated subfolder for 4 REST API routes for better organization

I'm struggling to figure out why my .get('/:post_id') route isn't working... My project's folder structure looks like this: app.js routes --api ----blog.js The blog.js file is located in the routes/api folder. In app.js, I&apo ...

Are there specific elements that fall under the umbrella of CSS?

Code is causing some red boxes to appear unexpectedly. User agent: Chrome/80.0.3987.149 Linux x86_64 Here is the code snippet: <html lang="en"> <head> <meta charset="utf-8"> <title>Flow</title> ...

Tips for executing a callback function when triggering a "click" event in jQuery?

Having trouble triggering a custom event in the callback of a trigger call. Attempted solutions: var $input = $( ".ui-popup-container" ).find( "input" ).eq(2); function runtests () { console.log("clicked the input"); }; $input.trigger('click&ap ...

A guide on using .map() with meta tags in Next.js

My goal is to map the content of meta, but currently my code is replicating multiple instances of the entire meta tags. Here is the code I have: {general.head.articleAuthor.en.map(( ) => ( <meta property="article:author" content={general.h ...

Update the CSS dynamically using JavaScript or AngularJS

Is there a way to dynamically modify this CSS style using JavaScript or in an Angular framework? .ui-grid-row.ui-grid-row-selected > [ui-grid-row] > .ui-grid-cell{ background-color: transparent; color: #0a0; } .ui-grid-cell-focus ...

Establishing a client cookie will help deter any attempts at re-registering

Due to the inability to run server-side code, I am limited in implementing a PHP session for a registration form. Instead, I have opted to utilize a client cookie to ensure that each person can only register once with a unique email address. After reading ...

Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values. Here is the co ...

How to manage a POST request in a GET route using express.js

Exploring the world of Express and Node.js together for the first time has brought me face to face with what appears to be a simple roadblock. I've set up an API route that utilizes the GET method. Here's the route: app.get('/api/v1/all&apo ...

Create a division that will remain visible on the screen and allow scrolling when a certain class is

Having some trouble with a fixed class div that is not continuing to scroll after the class is removed on scroll. I've attempted to fix this issue but the div keeps getting hidden instead of continuing to scroll. If anyone has any advice or can poin ...