zoukankan      html  css  js  c++  java
  • 函数的返回值是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

  • 相关阅读:
    php数组函数array_slice、array_splice
    php使用curl_init()和curl_multi_init()多线程的速度比较详解
    mysql忘记root密码
    php的RSA非对称加密
    phpstudy开启xdebug
    Centos7系统yum安装软件 No more mirrors to try
    python数据分析与数据可视化入门级
    第一周博客总结
    python——pandas初体验
    第十六周博客总结
  • 原文地址:https://www.cnblogs.com/ZerlinM/p/14611769.html
Copyright © 2011-2022 走看看