这里有一个脚本,它可以多个AJAX请求从REST服务获得多个股票报价。然而,我得到的结果是不正常的。
这是我的控制台日志序列TSLA -> TSLA -> -> 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]);
}
});发布于 2013-11-22 23:40:50
问题在handleSuccess中--它增强了每个结果的jsonResultArray,并每次调用回调:
jsonResultArray.push(jsonResult)
this.fCallback(jsonResultArray);我想你可以:
this.fCallback(jsonResult) (当每个结果到达时,这将多次调用回调)。this.resultCount,在每个错误/成功处理程序上增加它,并将其与请求的数量进行比较。但是,如果您希望同时运行多个QuoteService调用,这就会变得更加复杂。发布于 2013-11-22 23:59:51
由于您使用的是jQuery,有一种简单的方法可以使回调只在所有请求完成后才被调用。请参阅http://api.jquery.com/jQuery.when/
// I removed error handling, you'll have to do that
StockQuotes.QuoteService = function(sSymbol, fCallback) {
var reqs = [];
for (var i=0; i < sSymbol.length; i++) {
reqs.push($.ajax({
data: { symbol: sSymbol[i]},
url: "http://dev.markitondemand.com/Api/v2/Quote/jsonp",
dataType: "jsonp",
async: "false"
}));
}
$.when.apply($, reqs).done(function(){
fCallback.apply(arguments);
});
});发布于 2013-11-22 23:40:54
无法确定您的请求将得到响应的顺序。这些请求可以在整个互联网上遵循不同的路径,并且服务器可以以不同的顺序响应它们。您可以做的是等待所有请求都得到响应,然后按照正确的顺序处理它们。
https://stackoverflow.com/questions/20156459
复制相似问题