数组中的值无法在提取代码块外部访问

时间:2018-10-19 19:30:34

标签: javascript arrays api object fetch

如果我尝试console.log数组'profiles',则只有在获取代码块中,外部获取代码块中的数组为空时,才能得到结果。有人知道这是怎么回事吗?

我删除了一些变量以减少代码,但是问题仅发生在获取代码块之外,换句话说,发生在函数getTinderProfiles()之外。

虽然我清楚地将person对象的数据存储在数组“配置文件”中,但我认为记录该数组的数据没有问题。

谢谢!

let url = 'https://randomuser.me/api/?results=11';
let profiles = [];
let Person = new Object();

function getTinderProfiles() {
  fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (tinderUsers) {

  // Get 10 users and put data in object
  let randomUser = tinderUsers.results;
  for (let i = 0; i < randomUser.length; i++) {
    Person = {
      picture: randomUser[i].picture.large,
      name: randomUser[i].name.first + ' ' + randomUser[i].name.last,
      age: 'Age: ' + randomUser[i].dob.age,
      location: randomUser[i].location.city + ' ' + randomUser[i].location.postcode + '<br>' + randomUser[i].location.street,
    }
    // console.log(JSON.stringify(Person));

    // Add fetched persons to profiles array
    function pushToProfiles() {
      profiles.push(Person);
      console.log(profiles);
    }
    pushToProfiles();

  console.log(profiles[0]); // RESULTS !!!

});
}
 getTinderProfiles();
console.log(profiles); NO RESULTS !!!

2 个答案:

答案 0 :(得分:-1)

您正在调用的 getTindersProfile 函数包含一个异步函数(获取)。

意味着系统只会对 url 进行网络调用,而不会等待任何响应(异步)。因此该函数将结束并继续执行下一个函数 console.log

仅当响应准备就绪时,系统才会在 then (承诺)中执行功能。

因此, console.log 在创建和填充概要文件数组的循环之前执行。

要解决您的问题,只需创建一个仅在响应准备就绪时才应执行的回调。

let url = 'https://randomuser.me/api/?results=11';
let profiles = [];
let Person = new Object();

function getTinderProfiles(callback) {
  fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (tinderUsers) {

  // Get 10 users and put data in object
  let randomUser = tinderUsers.results;
  for (let i = 0; i < randomUser.length; i++) {
    Person = {
      picture: randomUser[i].picture.large,
      name: randomUser[i].name.first + ' ' + randomUser[i].name.last,
      age: 'Age: ' + randomUser[i].dob.age,
      location: randomUser[i].location.city + ' ' + randomUser[i].location.postcode + '<br>' + randomUser[i].location.street,
    }
    // console.log(JSON.stringify(Person));

    // Add fetched persons to profiles array
    function pushToProfiles() {
      profiles.push(Person);
      console.log(profiles);
    }
    pushToProfiles();

  console.log(profiles[0]); // RESULTS !!!
  // Call the call back function here
   callback();

});
}
 getTinderProfiles(function(){
     console.log(profiles); // RESULTS AVAILABLE !!!
 });

答案 1 :(得分:-1)

由于getTinderProfiles是异步的,因此可以使用回调函数来使用它的结果。处理fetch的结果后,可以调用回调函数。重要的是在profiles内声明getTinderProfiles。如果您在getTinderProfiles之外声明它,则它将始终为空。您的代码缺少括号function (tinderUsers)

function getTinderProfiles(useProfiles) {
    let profiles = [];
    fetch(url).then(function (response) {
        return response.json();
    }).then(function (tinderUsers) {
      // Get 10 users and put data in object
        let randomUser = tinderUsers.results;
        for (let i = 0; i < randomUser.length; i++) {
            Person = {
                picture: randomUser[i].picture.large,
                name: randomUser[i].name.first + ' ' + randomUser[i].name.last,
                age: 'Age: ' + randomUser[i].dob.age,
                location: randomUser[i].location.city + ' ' + randomUser[i].location.postcode + '<br>' + randomUser[i].location.street,
            }
         profiles.push(Person);    
         }
      useProfiles(profiles)
      });
    }


function useProfiles(profiles){
    console.log(profiles);
}