我正在构建一个反应本机应用程序,并与我的承诺遇到了问题。该代码以前有效,但是现在出于某种原因,我的承诺之一是独自解决"不确定"而没有执行...我包括代表代表应用程序组件流的代码,逻辑开始于componentdidmount((
我已经使用传统承诺重新编码了。
async componentDidMount() {
console.log('call 1');
let location = await this.getPermissions();
console.log('finish async');
console.log(location);
}
getPermissions = async () => {
console.log('start 1');
// Other logic here to determine platform, resulting in the next call
console.log('call 2');
let location = await this.getPosition();
console.log('respond 1');
console.log(location);
return location;
}
getPosition = async () => {
console.log('start 2');
// Promise resolves here with "undefined" before the
// getCurrentPosition finishes executing
navigator.geolocation.getCurrentPosition(
position => {
// Logic to find closest
console.log('respond 2');
console.log(closest);
return closest;
}
);
}
因此,在日志语句中,应适当的流程 - 致电1 - 开始1 - 致电2 - 开始2 - 回应2- 结果 - 回应1- 结果 - 完成异步 - 结果
我得到的输出是 - 致电1 - 开始1 - 致电2 - 开始2 - 回应1- 不明确的 - 完成异步- 不明确的 - 回应2 - 结果----这个结果是正确的,但是承诺过早解决了未定义的
您需要使getPosition返回诺言。
getPosition = async () => {
console.log('start 2');
// Promise resolves here with "undefined" before the
// getCurrentPosition finishes executing
return navigator.geolocation.getCurrentPosition(
position => {
// Logic to find closest
console.log('respond 2');
console.log(closest);
return closest;
}
);
}