自学成才,苦苦挣扎,了解回调是如何运作的。
我的回调处理函数无法访问数组的各个元素,即:
但是,“ResultsArray [1]”在Firefox控制台中直接执行时效果很好。
我究竟做错了什么?
<script>
ArrayOfTickers=["SPY","DIA","IWM","C"];
ResultsArray=[];
SomeArray=[]
function Main(Array, callback){
recursive(0);
function recursive(counter) {
if (counter < ArrayOfTickers.length) {
fetch("https://api.iextrading.com/1.0/stock/" + ArrayOfTickers[counter] + "/time-series")
.then(function(response) {
response = response.json()
.then(function(data) {
ResultsArray[counter]=data
})
})
recursive(counter+1);
} else {
callback(ResultsArray);
};
} //End recursive function
}; //End Main Function.
Main(ArrayOfTickers, function(ResultsArray){
console.log(ResultsArray)
})
</script>
首先,如果您要使用回调,请使用如下错误优先回调:
const results = [];
function main(cb) {
(function recursive(counter) {
if (counter >= ArrayOfTickers.length) {
return cb(null);
}
const url = `https://api.iextrading.com/1.0/stock/${ArrayOfTickers[counter]}/time-series`;
fetch(url)
.then(function (response) {
return response.json();
})
.then(function (data) {
results.push(data);
recursive(counter + 1);
})
.catch(cb);
})(0)
}
main(function (err) {
if (err) throw err;
console.log(results)
});
//但是使用这样的承诺可能会更好
function main() {
const recursive = function (counter) {
if (counter >= ArrayOfTickers.length) {
return;
}
const url = `https://api.iextrading.com/1.0/stock/${ArrayOfTickers[counter]}/time-series`;
return fetch(url)
.then(function (response) {
return response.json();
})
.then(function (data) {
results.push(data);
return recursive(counter + 1);
});
};
return recursive(0);
}
main().then(function(){
// check results
})
.catch(function(err){
// handle error
});
“的console.log(ResultsArray)[1])”
应该是console.log(ResultsArray[1])
,坏括号。