rez包含未决的Promise。我需要解决它,并暂停其他代码,直到解决为止:
function getCoordinates() {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
}
async function getAddress() {
await getCoordinates();
}
const rez = getAddress();
alert('wait for rez');
我知道我可以做类似getAddress().then(function () { alert('wait for rez')} );
的事情,但是有没有办法继续不在then
范围之内?
答案 0 :(得分:0)
您还需要await
进行异步操作:
(async function(){
function getCoordinates() {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
}
async function getAddress() {
await getCoordinates();
}
const rez = await getAddress();
alert('wait for rez');
})()
答案 1 :(得分:0)
就像注释函数一样,调用promise必须为async
,否则它将返回未决promise。
$(window).load(async function () {
var rez = await getCoordinates();
alert(rez.coords.latitude);});
function getCoordinates() {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
});};