如何从另一个范围返回值

时间:2019-11-12 19:02:47

标签: javascript reactjs ecmascript-6 axios

我在javascript中的函数内有一个函数。我在最内部的函数中得到了值,但我需要在最外部的函数中返回它。像这样:

import convertPrice from "./convertPrice";
import getCountryInfoByLanguage from "./getCountryInfoByLanguage";
import axios from "axios";
export default (language, price) => {
  let countryCode, currency, formattedPrice;

  navigator.geolocation.getCurrentPosition(position => {
    axios
      .get(
        `http://api.geonames.org/countryCodeJSON?lat=${
          position.coords.latitude
        }&lng=${position.coords.longitude}&username=...`
      )
      .then(response => {
        countryCode = getCountryInfoByLanguage(
          response.data.languages.split(",")[0]
        ).countryCode;
        currency = getCountryInfoByLanguage(
          response.data.languages.split(",")[0]
        ).currency;
        const convertedPrice =
          Math.round(convertPrice(price, currency) * 10) / 10;
        formattedPrice = convertedPrice.toLocaleString(countryCode, {
          style: "currency",
          currency: currency
        });
        console.log(formattedPrice);
        return formattedPrice; //This is where the value gets properly returned
      });

  });
    //this is where I want the value to be returned
};

1 个答案:

答案 0 :(得分:1)

由于您正在处理承诺,因此您始终可以退还它们并在最后调用最终的then

import convertPrice from "./convertPrice";
import getCountryInfoByLanguage from "./getCountryInfoByLanguage";
import axios from "axios";
export default (language, price) => {
  let countryCode, currency, formattedPrice;

  navigator.geolocation.getCurrentPosition(position => {
    return axios
      .get(
        `http://api.geonames.org/countryCodeJSON?lat=${
          position.coords.latitude
        }&lng=${position.coords.longitude}&username=filipk268`
      )
      .then(response => {
        countryCode = getCountryInfoByLanguage(
          response.data.languages.split(",")[0]
        ).countryCode;
        currency = getCountryInfoByLanguage(
          response.data.languages.split(",")[0]
        ).currency;
        const convertedPrice =
          Math.round(convertPrice(price, currency) * 10) / 10;
        formattedPrice = convertedPrice.toLocaleString(countryCode, {
          style: "currency",
          currency: currency
        });
        console.log(formattedPrice);
        return formattedPrice; //This is where the value gets properly returned
      });

  }).then((data) => {
      console.log(data);
  })
};

请注意,我正在返回axios调用,该调用返回了一个Promise,您甚至可以返回navigator.geolocation.getCurrentPosition,它可以作为Promise在当前范围之外访问。