内部功能响应有效,但外部响应无效。异步/等待问题?范围问题?

时间:2019-05-25 14:34:47

标签: javascript asynchronous scope async-await

我遇到一个问题,在函数geo.find中,console.log('Inner Response')返回正确的数据。但是,当我分配response = response [0] .location时,console.log('外部响应')返回未定义。这是异步/等待问题还是范围?

我已经尝试调试和尝试其他解决方案达数小时之久,但仍然遇到同样的问题。有人可以告诉我发生了什么事吗?

// Imports: Dependencies
const firebase = require('firebase');
const geocoder = require('google-geocoder');

// Imports: Data (Array Of Objects)
const originalData = require('../data/data');

// Reverse Geocode
const reverseGeocode = async (array) => {
  try {
    // New Data
    let newData = [];

    // Geocoder
    let geo = geocoder({
      key: 'API_KEY_HERE',
    });

    // Iterate Over Original Data
    for (let i = 0; i < array.length; i++) {
      // Response
      let response = null;

      // Latitude/Longitude
      let latitude = null;
      let longitude = null;

      // Address Details
      let street = json[i].street;
      let city = json[i].city;
      let state = json[i].state;
      let zipCode = json[i].zip_code;

      let fullAddress = await street.concat(' ', city).concat(' ', state).concat(' ', zipCode);

      // Google Geocoding API
      await geo.find(fullAddress, async (error, response) => {
        // Check For Errors
        if (error) {
          console.log(error);
        }

        // Assign Response
        response = response[0].location;

        // Check Response (Inner)
        console.log('Inner Response');
        console.log(response);
      });

      // Check Response (Outer)
      console.log('Outer Response');
      console.log(response)
      break;
    }
  }
  catch (error) {
    console.log(error);
  }
}

reverseGeocode(originalData);

0 个答案:

没有答案