我如何根据返回给我的值重复此函数来调用 api? Javascript
How do i repeat this function to call the api depending on the value that is returned to me ? Javascript
我想这是一个新手问题,但我遇到了一个问题,我想重复获取数据的操作并向 api 重复发出 post 请求,直到数据我接收是我想要的具体内容,我该怎么做以及我的代码做错了什么?到目前为止,在此先感谢您的帮助! :)
function diceBet(){
do {
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"x-access-token": api,
},
body: JSON.stringify(
bodyReq
)}).then(function(resp){
return resp.json()
}).then(function(respData){
console.log(respData);
})
}while(respData.data.diceRoll.result <= 99)}
您可以使用 async
函数和 await
。
async function diceBet() {
let respData;
do {
respData = await (await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"x-access-token": api,
},
body: JSON.stringify(
bodyReq
)
})).json();
} while (respData.data.diceRoll.result <= 99)
}
你也可以写一个 if
循环,但是就像上面提到的,使用 async
& await
。我个人更喜欢 if
循环,但我想这并不重要。
async function diceBet() {
await ( .. // fetching here )
}
if(result < 99) diceBet() // call your function again until condition is met
我想这是一个新手问题,但我遇到了一个问题,我想重复获取数据的操作并向 api 重复发出 post 请求,直到数据我接收是我想要的具体内容,我该怎么做以及我的代码做错了什么?到目前为止,在此先感谢您的帮助! :)
function diceBet(){
do {
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"x-access-token": api,
},
body: JSON.stringify(
bodyReq
)}).then(function(resp){
return resp.json()
}).then(function(respData){
console.log(respData);
})
}while(respData.data.diceRoll.result <= 99)}
您可以使用 async
函数和 await
。
async function diceBet() {
let respData;
do {
respData = await (await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"x-access-token": api,
},
body: JSON.stringify(
bodyReq
)
})).json();
} while (respData.data.diceRoll.result <= 99)
}
你也可以写一个 if
循环,但是就像上面提到的,使用 async
& await
。我个人更喜欢 if
循环,但我想这并不重要。
async function diceBet() {
await ( .. // fetching here )
}
if(result < 99) diceBet() // call your function again until condition is met