等待退还未决承诺

时间:2018-11-02 20:03:48

标签: javascript promise async-await

此示例中的

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范围之内?

2 个答案:

答案 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);
});};