这是我的代码
let loadInitialImages = ($) => {
let html = "";
let images = new Array();
const APIURL = "https://api.shutterstock.com/v2/images/licenses";
const request = async() => {
const response = await fetch(APIURL, { headers: auth_header() } );
const json = await response.json();
json.data.map((v) => images.push(v.image.id)); //this is where the problem is
}
request();
// I can see the contents of the array when I log it.
console.log(images);
// But I can't see any elements when logging this way:
images.map((id) => console.log(id));
}
一切在这里都可以正常工作,但是问题是当我将元素推入数组时,它从数组括号[]
中消失了,下面是我的数组的屏幕截图:
我无法在此处遍历数组。
请参阅此处的数组括号。元素似乎在[1, 2, 3]
答案 0 :(得分:2)
由于您的request
函数是async
,因此您需要将其结果视为Promise
。
这也是为什么您在chrome控制台中看到它表示不同的原因。将打印一个空数组,但是控制台中的引用是动态更新的,因此您仍然可以展开它并查看其内容。
如果要静态记录数组的内容,可以使用JSON.stringify
之类的东西来打印它。这将在记录日志时打印出表示阵列确切状态的字符串表示形式。
// You will need to check the output in the browser console.
// Your code could be reduced to this:
const a = [];
setTimeout(() => a.push(1, 2), 100);
console.log('a:', a);
// A filled array logs differently:
const b = [1, 2];
console.log('b:', b);
// Stringify gives you a fixed state:
const c = [];
setTimeout(() => c.push(1, 2), 100);
console.log('c:', JSON.stringify(c));
关于代码,除了等待request()
之外,如果您正在使用map
,则应该利用of how it works。您可以使用它来生成整个数组,而无需使用push
。如果仍然要使用数组并对其使用push()
,则应使用json.data.forEach
而不是json.data.map
,因为它不会复制数组。
// Making your function `async` so you can `await` for the `request()`
let loadInitialImages = async ($) => {
let html = "";
const APIURL = "https://api.shutterstock.com/v2/images/licenses";
const request = async () => {
const response = await fetch(APIURL, { headers: auth_header() } );
const json = await response.json();
// Array.map will return a new array with the results of applying
// the given function to the original array, you can use that as
// an easy way to return your desired array.
return json.data.map((v) => v.image.id);
}
// Since request() is async, you need to wait for it to complete.
const images = await request();
// Array.forEach lets you iterate over an array without generating a
// copy. If you use map here, you would be making an unneeded copy
// of your images array.
images.forEach(i => console.log(i));
}
答案 1 :(得分:-1)
下面的代码段演示了您的问题(您的情况是arr1
,您想使用arr2
)。
如果loadInitialImages
不能async
,请使用arr3
方案。
async function main(){
let arr1 = [], arr2 = [], arr3 = [];
const getArray = ()=> (new Promise(resolve=>setTimeout(()=>{resolve([1,2,3])},1000)))
async function request(arr, number){
var result = await getArray();
result.forEach((el)=>(arr.push(el)))
console.log(`inner${number}`, arr)
return result;
}
request(arr1, 1);
console.log("outer1", arr1)
await request(arr2, 2);
console.log("outer2", arr2)
request(arr3, 3).then(()=>{
console.log("then3",arr3)
})
console.log("outer3", arr3)
}
main();
答案 2 :(得分:-2)
我认为问题在于在填充数组之前会触发console.log(),并且因为console.log使用引用工作,所以它会同时打印数组的状态(当它为空时以及在使用.map填充后) )
您可以测试此代码吗? 控制台就在循环之后
let loadInitialImages = ($) => {
let html = "";
let images = new Array();
const APIURL = "https://api.shutterstock.com/v2/images/licenses";
const request = async() => {
const response = await fetch(APIURL, { headers: auth_header() } );
const json = await response.json();
json.data.map((v) => images.push(v.image.id)); //this is where the problem is
console.log(images);
}
request();
}
let loadInitialImages = ($) => {
let html = "";
let images = new Array();
const APIURL = "https://api.shutterstock.com/v2/images/licenses";
const request = async() => {
const response = await fetch(APIURL, { headers: auth_header() } );
const json = await response.json();
json.data.map((v) => images.push(v.image.id)); //this is where the problem is
console.log(images);
}
request();
}
loadInitialImages();