javascript - 如何从另一个范围返回值
问题描述
我在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
};
解决方案
由于您正在处理 Promise,因此您始终可以返回它们并在最后调用 final 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 调用,它返回一个承诺,您甚至可以返回navigator.geolocation.getCurrentPosition
它可以作为当前范围之外的承诺访问。
推荐阅读
- javascript - 如何获取对象的属性名称并在 javascript 中使用该属性名称
- reactjs - You may need an appropriate loader to handle this file type.
- ssl - 如果我要反向代理子域,我应该使用什么 SSL 证书?
- c# - OWIN Authentication.GetExternalLoginInfo() 不适用于linkedin,但适用于其他人
- java - 我在 okhttp 库中没有看到我与 Picasso 一起使用的照片?
- angular - PrimeNg
排序 - python - Pandas 只在 excel 中编写部分代码
- xaml - 如何通过在 Xamarin 中调用 API 在 UI 上显示数据
- string - 如何在 Bash 脚本中连接字符串变量
- c - 我在 C 程序中对数组进行排序时出错