简体   繁体   中英

Calling another module function as callback [ES6]

I have a question regarding ES6 modules and how to correctly call functions between them as a callback.

Take "page_API.js", Upon data being recieved the callback function is called

// Make a call to our server, Once we've recieved data we'll call our callback

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

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

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

Now in my "xml_functions.js" where I handle this requestExecuteAsync and more, I would like to call the dataRecieved once the server has responded.

Previously the codebase I work with consisted of many JS files, with all functions living in the global namespace, so the function worked like this

// once data has been retrieved from server
if (callbackparamsArr.length) {
    window[callback](res, callbackparamsArr);
} else {
    window[callback](res);
}

However now the callback function is undefined in the window as it no longer has scope of dataRecieved.

I've tried including the dataRecieved function inside the xml_functions

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

and then just call

[callback](res)

but due to the "dataRecieved" import getting given a different string as defined in requestExecuteAsync (EG it will be called "_Data_Recieved_" instead of "dataRecieved" i'm not sure what to do.

Any help would be much appreciated!

Thanks

You should not pass the name of the callback function you want to call. Just 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);
    …
}

But since you're using ES6, you might want to have a look at promises so that you don't need to pass callback functions around at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM