Invoking a different module function as a callback in ES6

Question: I am facing an issue with ES6 modules regarding calling functions between them as a callback.

In "page_API.js", the callback function is invoked upon receiving data.

// Initiating a server request, triggering the callback upon data reception
import {requestExecuteAsync} from "../xml_functions";

export const getData = () => {
    requestExecuteAsync('api/getData', "dataRecieved");
};

export const dataRecieved = () => {
    alert('Received Data');
};

Now in my "xml_functions.js" where I manage requestExecuteAsync and more operations, I intend to execute the dataRecieved function after obtaining a response from the server.

Prior to this, our codebase comprised numerous JS files where all functions were global, enabling the following implementation:

// Upon data retrieval from the server
if (callbackparamsArr.length) {
    window[callback](res, callbackparamsArr);
} else {
    window[callback](res);
}

However, the callback function is now undefined in the window as it lacks the scope of dataRecieved.

I attempted to include the dataRecieved function within xml_functions:

import { dataRecieved } from "../MyPage/MyPage_API.js";

and then simply call:

[callback](res)

Nevertheless, due to the "dataRecieved" import being assigned a different string within requestExecuteAsync (e.g. "_Data_Recieved_" instead of "dataRecieved"), I'm uncertain about how to proceed.

Any assistance on this matter would be greatly appreciated!

Thank you

Answer №1

It is recommended not to pass the name of the callback function you wish to call. Instead, simply pass the function itself:

import {requestExecuteAsync} from "../xml_functions";

export function getData() {
    requestExecuteAsync('api/getData', dataReceived);
//                                     ^^^^^^^^^^^^
}
export function dataReceived() {
    alert('Recieved Data');
}

export function requestExecuteAsync(path, callback) {
    …
    if (typeof callback == "function") callback(res);
    …
}

Considering you are using ES6, it might be beneficial to explore promises as an alternative so that passing around callback functions becomes unnecessary.

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

Mongoose: When attempting to cast the value "undefined" to an ObjectId at the _id path for the model "", a CastError occurred

I am working on developing an app using the MERN stack. However, I encountered an issue when trying to add a user to the current database. The error message reads as follows: CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model ...

Unusual perspective of JSON with ng-jsoneditor in AngularJS

Currently, I have integrated ng-jsoneditor into my AngularJS application to display and format JSON data. I found guidance on how to implement this from both here and here. Here is the HTML code snippet: <div ng-jsoneditor="onLoad" ng-model="vm. ...

What is the most effective method for determining the distance between two UK Postcodes?

Can you suggest a reliable method for calculating the distance between two UK postcodes in order to determine if they are within range? I do not intend to display a map, but instead provide a list of results for valid locations. For example, showing loca ...

AngularJS and ExpressJS clash in routing (Oops, Crash!)

When setting up routing in angularjs and expressjs, I have created app.all('/*'...) to enable rendering index.html. However, whenever I use /*, the page crashes with an "Aw, Snap!" message. angularjs home.config(function($routeProvider,$locatio ...

The error message "element.getAttribute is not defined" is common when using the Perfect

I'm facing an issue while trying to implement the perfect-scrollbar plugin on my AngularJS website. The error I encounter is as follows: TypeError: element.getAttribute is not a function at getId (http://localhost/Myproject/js/lib/perfect-scrollb ...

Swagger is unable to locate a user schema when utilizing Yaml files

Hello, I am a beginner using Swagger and trying to create simple endpoint documentation. However, I am facing an issue with my schema type and cannot figure out what's wrong. To start off, I organized my folder structure in the root src directory whe ...

Searching for a specific word within a given string using a loop

Currently, I'm developing a 'for' loop to search for my name, Andrew, in a given text and store the occurrences in an array. However, there seems to be an issue with the implementation. /*jshint multistr:true */ var text = ("Andrew is real ...

Is it possible to add a jQuery-generated element to pure vanilla JavaScript?

I am facing a challenge in creating a new notification div when an event is triggered. Ideally, I would normally achieve this using jQuery by utilizing something like $("myDiv").append(newDiv). However, in this case, the item selector to which the new div ...

Do not continue submitting if the innerHTML matches the specified value

I am currently working on a web page that verifies if an email entered by the user is available in the database. If it is, I need to prevent the form from being submitted. To achieve this, I have implemented Ajax for real-time checking of the email and di ...

Using jQuery to fetch and read the source code of a specified URL

I'm facing an issue with extracting the source code of a website URL into a variable. Here is my current approach: <script type="text/javascript"> debugger; $(documnet).ready(function () { var timer = $.ajax({ type: ...

What causes the child component to re-render when only the prop is changed and useCallback is used?

Child component will only re-render if its prop (numberModifier) is changed. The numberModifier uses useCallback with no dependencies, so it remains constant. To test this, I alter the value of "online" in the Application component which is a prop of Pare ...

Tips for dynamically updating data with on.click functions in D3

Implementing pack layout with D3 v4 is my current task, and I am looking to adjust the circle sizes based on the values "funds" and "spend" in my csv file. The following code successfully scales the circles: rank(funds) rank(spend) However, the on.click ...

Issue: Nest is unable to determine dependencies for the AwsSnsService (?)

I've been attempting to connect a service from one module to another, but I keep encountering this error message: Error: Nest can't resolve dependencies of the AwsSnsService (?). Please ensure that the argument function() {\n if (klass !== ...

Issue with Dropdown Menu functionality while using multiple dropdown options

I am currently experimenting with dropdown menus from W3Schools and have encountered an issue when trying to implement two dropdown options. The code works fine for a single dropdown, but when I try to add a second one using GetElementsByClassName instead ...

Encountering issues with the phaser framework while setting up a server on xampp, faced with errors in javascript and html

Recently, I've been working on a game using Phaser and encountered some issues while trying to run the code in XAMPP. The game's base is located at htdocs/itw/test.html, with the necessary pngs and json file stored in htdocs/itw/assets/. The pngs ...

Removing an item from a Redis list using Node.js

Recently, I encountered a challenge involving managing a list in Redis using Node.js. I successfully stored a list with the following code snippet: client.rpush(['room_'+room, data.customClient], function(err, reply) { client.lrange(&ap ...

What is the best way to make a canvas element fit the entire browser window without causing scroll bars to appear?

My window size isn't working properly, despite attempting the following code: Javascript var game; function game() { this.canvas = document.getElementById('canvas'); this.canvasWidth = window.innerWidth; this.canvasHeight = wi ...

Is it possible to simultaneously employ two asynchronous functions while handling two separate .json files?

Is it possible to work with 2 .json files simultaneously? My attempt did not succeed, so I am looking for an alternative method. If you have a suggestion or know the correct syntax to make this work, please share. And most importantly, does the second .j ...

Is there a way to navigate to the adjacent values in a json array?

I've been struggling with this issue for quite some time now. I have a list of items that can be moved to a div when clicked. My goal is to navigate through the items in the list (json) by clicking on Next and Previous buttons. As someone who is rela ...

Struggling to make the switch operational

I'm struggling to make this switch statement work. I want to have multiple conditions like in an if-else statement, but I can't seem to figure out how to add more than two conditions. function spriteAI1() { var posX = c2Sprite.p ...