Modify the array value and access it outside of an asynchronous function

Is there a way to set values in an array from an asynchronous function and access it outside of that function's scope?

I am working on a project where I need to randomize values in an array, so that I can assign images randomly to different div elements.

$scope.Resources = ResourceFetch.getResource().then(function(resources){
    $scope.img1 = JSON.stringify(resources.img1);
    $scope.img2 = JSON.stringify(resources.img2);
    $scope.img3 = JSON.stringify(resources.img3);
    $scope.img4 = JSON.stringify(resources.img4);

    var myArray = [$scope.img1, $scope.img2, $scope.img3, $scope.img4];
    console.log('myArray is ' + myArray); // <- Working as expected.

    var shuffledArray = [];

    ShuffleArray.getShuffled(myArray).then(function(array){
        shuffledArray = array;
        console.log('Shuffled array is ' + array); // <- Working fine.
        console.log('Shuffled array again ' + shuffledArray); // <- Everything seems good here
        });

   console.log('Shuffled array accessed from outside  ' + shuffledArray); // <- Nothing displayed.
});

Answer №1

Your code seems to be correct, although it's important to remember that getShuffled is likely asynchronous and may only complete after

console.log('The shuffled array outside is  ' + shuffledArray); // Note: No output here.

is executed.

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

Passing data as a parameter from the view to the controller using AngularJS

I am attempting to retrieve data from a view, which must be passed as a parameter in a function in order to populate an array in the controller. However, I am not receiving any objects in return. Here is what I have tried: VIEW <div ng-repeat="cssfram ...

Implementing Conditional Class Addition in React.js

Currently, I am utilizing Reactjs (Nextjs) to work on my project. The project consists of a "Home page" as well as several other pages such as about and services. To integrate these pages in Nextjs, I created "_document.js". However, I have encountered a ...

Running nodejs scripts within my HTML and JavaScript code

Using express, I send an HTML file to incoming GET requests: app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/public/index.html')); }); Within that HTML file, I included another JavaScript file, script.js, us ...

Developing a Highchart Graph using JavaScript

I am trying to develop a high chart graph. Check out my code on FIDDLE LINK. I have two values, a and b, for the x-axis and y-axis. The issue arises when the difference between a and b is minimal, such as when both are equal (-9). In such cases, the grap ...

What are the steps for integrating DoctorJS with Emacs?

Is there a method to utilize DoctorJS (formerly known as jsctags) in order to create a TAGS file specifically for Emacs? I have been researching this topic and it appears that it typically defaults to the vi tags style, although I may be overlooking a str ...

Steps for incorporating events on Jquery UI button

I have a question about utilizing Jquery UI for the first time. After successfully adding a button using Jquery UI, I am now interested in adding events for when a radio switch is turned on and off. When the radiobox is switched on, I want an alert window ...

Performing an HTTP GET request to an endpoint within a RESTful API

I am looking to integrate a feature in my web application that displays the list of online users on my website. To achieve this, I need to make an HTTP GET request to the URL which returns the user data in JSON format. The returned JSON data contains var ...

Ensure that the link's color remains constant and remove any styling of text-decoration

Attempting to create a customized header. My goal is to change the color and remove text decoration in the navbar. Below is my code snippet: ReactJS: import React from 'react'; import './Header.css'; function Header() { return ( ...

Encountering a 403 Forbidden error while attempting to access a website built with Next.js

Every time I try to access the Next.JS website that's been deployed on IIS using the HTTP address, I'm faced with this error message: Get http://...../_next/static/chunks/webpack-73760e2208a549db.js net:: ERR_ABORTED 403 (Forbidden) However, w ...

Encoding identification data from JSON using ColdFusion

Hello everyone, I've been puzzling over how to intercept and encrypt database record ID from a JSON request in ColdFusion. Below is the code I have so far, along with my unsuccessful attempt. Any assistance would be greatly appreciated. <cfquery ...

Tips for retrieving headers from a POST response using AngularJS $http

Before moving forward, it's important to note that this scenario occurs within a CORS environment. On Server #1 (http://localhost:33233), which is my main website hosting SOAP and WebAPI services, I have added the following lines to the Global.asax i ...

While making changes, I was anticipating a "for-of" loop to be used instead of a "for" loop

There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...) loop. Consider this straightforward code snippet: this.filters['1','2','3'....]; for (let i = 0; i < this.filters.length; i+ ...

The onChange event for React select is being triggered twice, incorrectly using the old value the second time

I am currently implementing React Select to display a list of items. When an item is changed, I need to show a warning based on a specific flag. If the flag is true, a dialog box will be shown and upon confirmation, the change should be allowed. After each ...

The markers from KML exported from My Maps are not showing up on the Google Maps JavaScript API

I have a map on Google My Maps that I want to showcase through the Google Maps JavaScript API. This way, I can easily merge multiple maps into one and add paths/markers without needing to code it all manually. Test out the map I'm using by clicking t ...

Angular- Table button placement

I have a requirement where I need to display a button in a table, but the button should only show when the "name" value is set to "False". If the "name" value is set to "True", then the button should not be displayed. This is my Json data: [ { ...

Retrieving an element by its id in Angular 2

Hi there, I'm having some trouble with a code snippet: document.getElementById('loginInput').value = '123'; When trying to compile the code, I keep getting this error message: "Property value does not exist on type HTMLElement ...

What is the process for resizing a texture render target following a window resize event?

My intention was to improve the texture quality, but instead of achieving my goal, I encountered an issue where the same texture is being stretched over a larger area, resulting in unwanted staircase artifacts. I tried updating various elements like camera ...

Tips for including vue-autonumeric in your webpack 2 setup

Encountering a problem while bundling the vue-autonumeric package with Webpack 2, where the dependency AutoNumeric is not being found properly. Although there is an alias set up in the configuration that works fine with webpack 3, it seems to fail when wo ...

The application encountered an exception and has ceased to respond, displaying a custom error page

I have a .NET application running on IIS 7 that is accessed from IE7. When a specific exception occurs, the page is redirected to a plain .htm page with a back button that should take the user back to the previous page. This exception handling is implement ...

Struggling to retrieve unpredictable data in a Vue.js component

Help! I'm trying to randomly display one of these names in my HTML, but I can't seem to make it work: Vue.component('modal', { template: '#modal-template', data: { items: [ { name: 'Elena' }, { na ...