首页 > 解决方案 > 为什么我需要使用回调函数来访问 Web api 的变量?

问题描述

const request = require('postman-request');


const geocode = (address) => {
  const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${address}.json?access_token=pk.eyJ1IjoibWVya3VyMTIzIiwiYSI6ImNrYjVndDk3bjBvNGEyeW16cHlid2txZ3YifQ.NGOWOq0yq0wvkhzDzjnUpQ&limit=1`;
  request({ url, json: true }, (error, response) => {
    const data = response.body;
    if (error) {
      return 1;
    } else if (data.message === 'Not Found' || data.features.length === 0) {
      return 1;
    } else {
      return {
        longitude: data.features[0].center[0],
        latitude: data.features[0].center[1],
        location: data.features[0].place_name,
      };
    }
  });
};

output = geocode("New York");

console.log(typeof output);

大家好,我知道代码不起作用,我应该使用回调函数,但我想知道为什么会这样。为什么我不能返回结果,在这种情况下是一个对象,并像往常一样访问它?

感谢您的每一个有用的回复!

标签: javascriptnode.jshttp

解决方案


推荐阅读