函數的返回值是promise 怎么解決


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM