gpt4 book ai didi

javascript - 多个 AJAX 请求乱序

转载 作者:行者123 更新时间:2023-11-28 04:35:49 25 4
gpt4 key购买 nike

我这里有一个脚本,它执行多个 AJAX 请求以从 REST 服务获取多个股票报价。但是我得到的结果是乱序的。

这是我的控制台日志序列 TSLA -> TSLA -> AAPL -> TSLA -> AAPL -> ATT

我的代码有什么问题吗?为什么我得到多次输出?

    var jsonResultArray = new Array();
var StockQuotes = {};
/**
* Define the QuoteService.
* First argument is symbol (string) for the quote. Examples: AAPL, MSFT, JNJ, GOOG.
* Second argument is fCallback, a callback function executed onSuccess of API.
*/
StockQuotes.QuoteService = function(sSymbol, fCallback) {
console.log("Entering quote serivce");
this.symbol = sSymbol;
this.fCallback = fCallback;
this.DATA_SRC = "http://dev.markitondemand.com/Api/v2/Quote/jsonp";
for(index in sSymbol){
this.makeRequest(sSymbol[index]);
console.log(sSymbol[index])
}
};
/**
* Ajax success callback. fCallback is the 2nd argument in the QuoteService constructor.
*/
StockQuotes.QuoteService.prototype.handleSuccess = function successHandler(jsonResult) {
console.log("Entering handle success");
jsonResultArray.push(jsonResult)
this.fCallback(jsonResultArray);
if(this.xhr) {this.xhr.abort();}
};
/**
* Ajax error callback
*/
StockQuotes.QuoteService.prototype.handleError = function errorHandler(jsonResult) {
console.log("Entering handle error");
console.error(jsonResult.Message);
};
/**
* Starts a new ajax request to the Quote API
*/
StockQuotes.QuoteService.prototype.makeRequest = function requestHandler(currentSymbol) {
console.log("Entering make request");
//Abort any open requests
// while (this.xhr) { }
//Start a new request
this.xhr = $.ajax({
data: { symbol: currentSymbol},
url: this.DATA_SRC,
dataType: "jsonp",
async: "false",
success: this.handleSuccess,
error: this.handleError,
context: this
});
};

new StockQuotes.QuoteService(["T","AAPL","TSLA"], function finalOutput(jsonResultArray) {
console.log("Entering final output");
for(i in jsonResultArray){
console.log(i);

//If all goes well, your quote will be here.
console.log(jsonResultArray[i]);

}

});

最佳答案

问题出在 handleSuccess 中——它为每个结果增加了 jsonResultArray,并且每次都调用回调:

jsonResultArray.push(jsonResult)
this.fCallback(jsonResultArray);

我想你可以:

  1. 只传递当前结果,this.fCallback(jsonResult)(这将多次调用回调,因为每个结果到达)。
  2. 或者仅在所有结果都返回时才运行回调。乍一看,您似乎可以简单地使用一个成员变量 this.resultCount,在每个错误/成功处理程序上递增它,并将它与请求数进行比较。但如果您想同时运行多个 QuoteService 调用,这会变得有点复杂。

关于javascript - 多个 AJAX 请求乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20156459/

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