我已经使用了 async function
并等待一个 API
命中并显示其当前上传的文件名,然后增加计数器 I 并转到下一个文件。
问题:async
和 await
工作正常,但在发出所有请求后调用 回调。
如何点击 API
并打印其名称,然后再寻找另一个文件以点击 API?
PS:我无法将回调更改为承诺,这是我组织中目前已定义的结构。
代码:
uploadCallback = () => {
console.log(currentFile)
}
const loop = async() => {
for (let i = 0; i < this.state.fln.length; i++) {
currentFile = obj.fln;
await uploadAPI(obj, this.uploadCallback);
console.log('currentFile:', i, currentFile);
}
};
答案 0 :(得分:0)
你可以尝试这样的事情:
uploadCallback = () => {
console.log(currentFile)
}
const loop = async() => {
for (let i = 0; i < this.state.fln.length; i++) {
currentFile = obj.fln;
const res = await uploadAPI(obj);
this.uploadCallback(res);
console.log('currentFile:', i, currentFile);
}
};
这将确保仅在 uploadAPI 完成后调用回调。
答案 1 :(得分:0)
您需要集成 Promise。这是 Pokemon API 的示例...
let thisstateflnlength = 5
const getAPI = (counter = 0) => {
if (counter <= thisstateflnlength) {
fetch("https://pokeapi.co/api/v2/pokemon/ditto").then(response => response.json()).then(data =>{
console.log(data.forms[0])
console.log(counter)
}).then(data => getAPI(counter+1))
}
}
getAPI()
计数器从 0 到 5 记录,每个 API 调用都是异步执行的。