我有一个url列表,我需要取回所有的,所以我使用取回,然后承诺。但是,我不知道如何返回承诺的结果。
let photos_info = [];
function get_photos(urls) {
var promises = urls.map((url) => fetch(url).then((y) => y.json()));
Promise.all(promises).then((results) => {
console.log("results:", results);
photos_info = [...results];
console.log("photos_info:", photos_info );
});
return photos_info ;
}
const list_of_photos = get_photos(urls);
console.log("result of the function", list_of_photos);
为什么list_of_photos返回一个空列表,而当在函数中打印photos_info时,它返回一个列表。
这是因为你的承诺。所有异步运行
因此return photos_info
将在得到未定义结果的响应之前运行。
改为:
let photos_info = [];
async function get_photos(urls) {
var promises = urls.map((url) => fetch(url).then((y) => y.json()));
await Promise.all(promises).then((results) => {
console.log("results:", results);
photos_info = [...results];
console.log("photos_info:", photos_info );
});
return photos_info ;
}
const list_of_photos = get_photos(urls);
console.log("result of the function", list_of_photos);
您在控制台日志中获得响应的原因是它在then
块中,该块仅在承诺响应成功后运行(这也是异步的)