gpt4 book ai didi

javascript - 调用另一个模块函数作为回调 [ES6]

转载 作者:行者123 更新时间:2023-11-30 11:48:10 26 4
gpt4 key购买 nike

我有一个关于 ES6 模块以及如何在它们之间正确调用函数作为回调的问题。

以“page_API.js”为例,收到数据后调用回调函数

// 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');
};

现在在我处理此 requestExecuteAsync 等的“xml_functions.js”中,我想在服务器响应后调用 dataRecieved。

以前我使用的代码库由许多 JS 文件组成,所有函数都位于全局命名空间中,所以函数是这样工作的

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

但是现在回调函数在窗口中是未定义的,因为它不再具有 dataRecieved 的范围。

我试过在 xml_functions 中包含 dataRecieved 函数

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

然后打电话

[callback](res)

但是由于“dataRecieved”导入得到了 requestExecuteAsync 中定义的不同字符串(例如,它将被称为“_Data_Recieved_”而不是“dataRecieved”,我不确定该怎么做。

如有任何帮助,我们将不胜感激!

谢谢

最佳答案

您不应传递要调用的回调函数的名称。只需传递函数本身:

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);

}

但是由于您使用的是 ES6,您可能想看看 promise,这样您就根本不需要传递回调函数。

关于javascript - 调用另一个模块函数作为回调 [ES6],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40238692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com