方法来清除数组,然后填充它,最后得到一个空数组



我目前正在尝试清空一个数组,然后在调用覆盖函数的每次迭代时用从API获取的信息填充它,所有这些都是用JavaScript实现的。

function getInfo() {
clearArray()
// call the API
callAPI()
// push arrayObjects into DOM
array.forEach(object => {
// do stuff with it
}
}

clearArray((将数组的长度设置为零:

function clearArray() {
array.length = 0
}

callAPI((是一个提取函数:

function callAPI() {
fetch(urlG)
.then(response => response.json())
.then(function(response) {
// parse and then push objects into global array
})
}

我非常确信callAPI((函数在不同的点上从console.log((-ing正确地完成了它的工作。

然而,当我在forEach语句之前控制台.log(array.length(时,它变成了0。我读到console.log在这种情况下可能不是最准确的,但:

  • 在clearArray((函数后面添加console.log(数组(-但在callAPI((之前-打印出中正确填写的数组控制台
  • 在callAPI((之后添加console.log(array(的方法相同呼叫
  • console.log(array.length(的任何位置都会导致0
  • 在调用每个函数之前和之后使用断点总是显示数组为空

我尝试使用回调来强制它等待,如下所示:

callAPI(回调(

function callAPI(callback) {
fetch(url)
.then(response => response.json())
.then(function(response) {
// do stuff
})
callback()
}

getInfo((:

function getInfo() {
// reset news array
clearArray()
// call the news APIs
callAPI(function() {
console.log(array.length)
// push arrayObjects into DOM
array.forEach(arrayObject => {
// do stuff
})
}
}

但我也遇到了同样的错误。

使用await获取(url(最终会出现同样的问题。

async function callAPI() {
let response = await fetch(url)
let json = response.json()
let results = json.response.results
// do stuff
}

我对JavaScript还是比较陌生的,所以如果需要任何进一步的信息,我绝对可以提供

在回调情况下,必须从其中一个then调用它。并且在callback中使用array.forEach

function handleData(array){
array.forEach(...);
}
function callAPI(callback) {
fetch(url)
.then(response => response.json())
.then(function(response) {
callback(response)
})
//or this, both are equivalent
then(callback)
}
callAPI(handleData);

对于async/await(promise(,您需要使callAPI成为一个异步函数并正确使用它:

async function callAPI() {
let response = await fetch(url)
//json() also returns a promise so you have to await that as well
let array = await response.json();
array.forEach(...);
}

async function callAPI() {
let response = await fetch(url)
let array = await response.json();
return array;
}
callAPI().then(function(array){
array.forEach(...);
})

代码之所以如此,是因为javascript在看到异步代码时不会停止。

这就是正在发生的事情。

当JavaScript进入函数getInfo时,它执行clearArray并转到下一条指令callAPI。然后它看到callAPI包含异步代码。然后它立即将这段异步代码发送到Web API来处理,这样它就不会等待了。然后转到下一个指令forEach(而异步代码仍由Web API执行(。此时,异步代码中的promise尚未解析,这意味着对象尚未被推入全局数组,因此数组仍然为空。

因此,这里有一种方法可以通过在callAPI函数中使用async/await来解决这个问题:

function async callAPI() {
const apiResponse = await fetch(urlG) //pause and get apiResponse before continuing execution
const jsonResponse = await apiResponse.json() //pause and get jsonResponse before continuing execution
//parse and then push objects into global array
//...
}

最新更新