Javascript 如何从另一个作用域返回值
我在javascript中的函数中有一个函数。我在最里面的函数中得到我的值,但我需要在最外面的函数中返回它。像这样:Javascript 如何从另一个作用域返回值,javascript,reactjs,ecmascript-6,axios,Javascript,Reactjs,Ecmascript 6,Axios,我在javascript中的函数中有一个函数。我在最里面的函数中得到我的值,但我需要在最外面的函数中返回它。像这样: import convertPrice from "./convertPrice"; import getCountryInfoByLanguage from "./getCountryInfoByLanguage"; import axios from "axios"; export default (language, price) => { let country
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
};
由于您正在处理承诺,因此您始终可以返回承诺并在最后调用最终的
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调用,它返回一个承诺,您甚至可以返回navigator.geolocation.getCurrentPosition
它将作为当前范围之外的承诺进行访问。这是否回答了您的问题?不,这不行。我得到navigator.geolocation.getcurrentposition是未定义的错误。您能检查是否定义了navigator.geolocation
?我在浏览器控制台中检查了它,它是。当我删除最后一个时,错误消失。然后()尝试理解我所做的,而不是复制粘贴我的代码。为什么我要尝试理解不起作用的代码?