函数的返回值是promise<pending>怎么解决

async 是“异步”的简写,而 await 可以认为是 async wait 的简写。所以应该很好理解 async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成。
另外还有一个很有意思的语法规定,await 只能出现在 async 函数中。

突然某天我写了个函数,然后调用的时候,发现返回的是promise的状态。但我在调用的函数里面打log, 是能打出来结果的,搜了很长时间才找到答案。最后也解决了。这里记录一下:

async function getMobile() {
  let mobile = await readLocalMessage('MOBILECODE', (result) => {
    if(result) {
      return result;
    }
  )
  return mobile;
}

getMobile().then(result => {
  console.log(result);
})

function readLocalMessage(keys, callBack) { // 调接口获取信息
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `/get?name=${keys}`, true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 300)) {
      let result = JSON.parse(xhr.responseText);
      if (result) callBack(result);
    }
  }
}

上面这个例子,readLocalMessage函数来调接口获取数据的,我们写了getMobile()函数来调用这个异步请求,这个函数用async, await写的。然后调用getMobile(),并通过then方法,来获取result。
但是这里获取失败了。
哪里出问题了?
首先上面的async, await返回的是一个promise对象。所以它肯定返回不了想要的result。只能是在resolve之后把结果给返回来。即使用了then方法,拿到的也是promise。
所以对上面代码做一下修改。

async function getMobile() {
  let mobile = await new Promise(resolve => { // 重点
    readLocalMessage('MOBILECODE', (result) => {
      if(result) {
        return resolve(result); // 重点
      }
    })
  })
  return mobile;
}

getMobile().then(result => {
  console.log(result);
})

function readLocalMessage(keys, callBack) { // 调接口获取信息
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `/get?name=${keys}`, true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 300)) {
      let result = JSON.parse(xhr.responseText);
      if (result) callBack(result);
    }
  }
}

下面的代码只是在getMobile这个函数外面包了一层。这样返回的结果就是resolve之后的结果了。
await 返回的值是promise返回的值。而promise返回的值是需要设定的,我们要的是resolve的,我们就返回resolve的。

附:
理解 JavaScript 的 async/await

posted @ 2021-04-02 17:29  ZerlinM  阅读(5633)  评论(1编辑  收藏  举报