Javascript 传递给函数的参数在fetch方法中不可见
那么为什么数组参数在秒中不可见呢Javascript 传递给函数的参数在fetch方法中不可见,javascript,Javascript,那么为什么数组参数在秒中不可见呢 let assignDataToArray = (array) => { fetch("data.json") .then(response => { if (response.ok) return response.json(); else throw new Error("Something went wrong
let assignDataToArray = (array) => {
fetch("data.json")
.then(response => {
if (response.ok)
return response.json();
else
throw new Error("Something went wrong with json file");
})
.then(result => array = [...result.data])
.catch(error => console.log(error));
}
let myArray = [];
assignDataToArray(myArray);
console.log(myArray);
我使用VS代码,甚至有人指出数组参数在秒范围内不可见。结果,承诺返回空数组,并且没有为数组参数赋值。正如您在注释中看到的,您在这里遇到了多个问题
fetch
是异步的。当fetch
执行其操作并运行中的内容时,您的程序将继续运行。因此,在恢复数据之前执行console.log
array=…
,您正在创建一个新数组,该数组的引用将与分配给myArray
的数组的引用不同。您可以通过改变原始数组而不是使用变量赋值来解决这个问题(=
)async/await
的方法:
let assignDataToArray = (array) => {
return fetch("data.json") // <----- Notice the return
.then(response => {
if (response.ok)
return response.json();
else
throw new Error("Something went wrong with json file");
})
.then(result => array.splice(0, array.length, ...result.data)) // Use of splice
.catch(error => console.log(error));
}
async function main() { // await can only be used inside an `async` function
let myArray = [];
await assignDataToArray(myArray); // <- await waits for this before running the next line
console.log(myArray);
}
main();
fetch
是异步的。不能简单地从异步函数返回。使用array=
,也会丢失对该数组的引用。见此:
let assignDataToArray = (array) => {
// ... same code as above ...
}
let myArray = [];
assignDataToArray(myArray)
.then(() => {
console.log(myArray);
/* Do something else from here */
});