gpt4 book ai didi

JavaScript 函数顺序

转载 作者:行者123 更新时间:2023-11-28 15:19:58 25 4
gpt4 key购买 nike

我正在制作一个 jquery 库来使用带有 json rpc 协议(protocol)的应用程序,但我遇到了一个小问题。这是显示代码的 fiddle (显然它无法工作):https://jsfiddle.net/L9qkkxLe/3/ .

;(function($) {
$.lib = function(options) {

var outputHTML = [],
plugin = this;

var APIcall = function(api_method, api_params) {
request = {};
request.id = Math.floor((Math.random() * 100) + 1);
request.jsonrpc = '2.0';
request.method = api_method;
request.params = (api_params) ? api_params : [];


$.ajax({
type: "POST",
url: "http://localhost:8898/jsonrpc",
data: JSON.stringify(request),
timeout: 3000,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', window.btoa(options.username + ":" + options.password));
},
success: function(data) {
handleData(data, api_method);
},
error: function(jqXHR, textStatus, errorThrown) {
log("Connection time out: can't reach it. Try changing the settings.");
isConnected = "false";
},
dataType: "json"
});


}

var handleData = function(data, method) {


if (method == "getgenres") {
outputHTML = data.result.genres; //I need data.result.genres to return in getgenres function
}

}


var log = function(msg) {
if (options.debug == true) console.log(msg);
}


plugin.getgenres = function() {
APIcall("getgenres");
return outputHTML; //This is sadly empty.
}


};
}(jQuery));

var init = new $.lib();
console.log(init.getgenres());

我需要 getgenres 函数返回 data.result.genres 但实际上它返回一个空数组,因为 getgenres 是首先调用的,并且只有在handleData函数向outputHTML提供我需要的值之后才调用。

最佳答案

您正在执行异步 AJAX 请求,这意味着您实际上无法立即取回数据。有两种方法可以解决您的问题:使其同步(简单但不明智)或使用回调(稍微复杂一点但普遍接受):

getgenres 函数中,您还可以接受一个参数:callback

plugin.getgenres = function(callback) {
/* Dont forget APIcall already took two parameters in, so callback has to be the third in line! */
APIcall("getgenres", false, callback);
}

现在修改您的 APIcall 函数以接受您的回调:

var APIcall = function(api_method, api_params, callback) { ... }

并从成功完成调用中调用回调 - 您可以简单地传递匿名函数,而不是将处理程序方法包装在函数中。因此,代替成功: function(data){ handle(data); },只需使用:

success: callback

我们将传递给它的anonymous函数将接收您传递给处理程序的数据作为其第一个参数。现在您可以执行以下操作:

var myGenres = [];
var init = new $.lib();
init.getgenres(function(data){
/* Now your data is actually loaded and available here. */
myGenres = data;
console.log(myGenres);
});

我想指出,有很多更好的方法来处理这个问题,包括将其转换为构造函数(更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain),而不是您所使用的函数和变量的奇怪合并。现在,以及使用 JS Promises(此处: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise )来使这变得更容易。但基本要点应该在这里。

更新(潜在实现)

因为我提到这可以通过一种我认为更易于阅读和使用的方式来完成。我不知道这方面的所有用例,但从提供的示例中,我会将代码更改为如下所示。另请注意,我不是 jQuery 插件方面的专家,因此我避免插入 jQuery,而只是将其用作简单的 AJAX 调用。

function getAjax(){
if(!window.jQuery || !window.$) throw("jQuery is required for this plugin to function.");
this.data = [];
this.request = '';
return this;
}
getAjax.prototype = {
createRequest : function(method, parameters){
this.request = {};
this.request.id = Math.floor((Math.random() * 100) + 1);
this.request.jsonrpc = '2.0';
this.request.method = method;
this.request.params = parameters || [];
return this;
},
callRequest : function(options, callback, error){
var self = this;
// We could also `throw` here as you need to set up a request before calling it.
if(!this.request) return this;
else {
$.ajax({
// We will allow passing a type and url using the options and use sensible defaults.
type: options.type || "POST",
url: options.url || "http://localhost:8898/jsonrpc",
// Here we use the request we made earlier.
data: JSON.stringify(this.request),
timeout: options.timeout || 3000,
beforeSend: function(xhr){
xhr.setRequestHeader(
'Authorization',
window.btoa( options.username + ":" + options.password)
);
},
// We will also store all the made request in this object. That could be useful later, but it's not necessary. After that, we call the callback.
success: function(data){
var store = {request:self.request, data: data};
self.data.push(store);
// Call the callback and bind `this` to it so we can use `this` to access potentially pther data. Also, pass the results as arguments.
callback(data, self.request.id).bind(self);
},
// Error function!
error: error,
dataType: options.dataType || "json"
});
}
return this;
}
}

// Example use

new getAjax().createRequest('getgenres').callRequest({
username: 'myusername',
password: 'mypassword'
}, function(data, id){
// Success! Do with your data what you want.
console.log(data);
}, function(e){
// Error!
alert('An error has occurred: ' + e.statusText);
console.log(e);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

关于JavaScript 函数顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31923411/

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