在提取函数中使用回调[重复]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在提取函数中使用回调[重复]相关的知识,希望对你有一定的参考价值。
为什么getscore()中的i
的值(它是第二个api的回调)是非顺序的,导致我的应用程序出现不希望的输出?
function getscore(sid, mid, callback) {
fetch("https://dev132-cricket-live-scores-v1.p.rapidapi.com/scorecards.php?seriesid=" + sid + "&matchid=" + mid, {
"method": "GET",
"headers": {
"x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
"x-rapidapi-key": "..."
}
})
.then(response => {
return (response.json());
})
.then(function(data2) {
callback(data2);
});
}
fetch("https://dev132-cricket-live-scores-v1.p.rapidapi.com/matches.php?completedlimit=6&inprogresslimit=7&upcomingLimit=9", {
"method": "GET",
"headers": {
"x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
"x-rapidapi-key": "..."
}
}).then((response) => {
return response.json();
}).then((MyJson) => {
console.log(MyJson);
for (let i = 0; i < MyJson.matchList.matches.length; i++) {
//some opeerations
console.log(i); //sequential
getscore(matchid, function(data) { //callback second api
console.log(i); //non-sequential
});
答案
问题是该API是同步的,并且您正试图以异步方式使用它
您将需要函数getScore返回一个诺言并在您的循环中链接诺言以实现此目标
function getscore(sid, mid) {
return new Promise(resolve => {
fetch(
'https://dev132-cricket-live-scores-v1.p.rapidapi.com/scorecards.php?seriesid=' + sid + '&matchid=' + mid,
{
method: 'GET',
headers: {
'x-rapidapi-host': 'dev132-cricket-live-scores-v1.p.rapidapi.com',
'x-rapidapi-key': '...'
}
}
)
.then(response => {
return response.json();
})
.then(function(data2) {
resolve(data2);
});
});
}
fetch(
'https://dev132-cricket-live-scores-v1.p.rapidapi.com/matches.php?completedlimit=6&inprogresslimit=7&upcomingLimit=9',
{
method: 'GET',
headers: {
'x-rapidapi-host': 'dev132-cricket-live-scores-v1.p.rapidapi.com',
'x-rapidapi-key': '...'
}
}
)
.then(response => {
return response.json();
})
.then(async MyJson => {
console.log(MyJson);
await Promise.all(
MyJson.matchList.matches.map(async val => {
await getscore(matchid);
})
);
});
另一答案
您对getscore方法的调用仅传入2个参数,您的声明调用了3个
以上是关于在提取函数中使用回调[重复]的主要内容,如果未能解决你的问题,请参考以下文章