异步/等待不等待响应,并返回Promise对象

时间:2018-08-31 15:33:46

标签: javascript asynchronous ecmascript-6 async-await

使用ES6,类和Aync / Await ...

目标是要有一个“ Api”类,该类通过fetch进行异步调用,并返回一些数据。...但是,即使是基础也无法正常工作。

这些snippet在主要js中运行,从而启动事件链:

let api = new Api();
let api_data = api.getLocation();

console.log(api_data);

getLocation方法如下,它将返回一些响应/数据。但是,从理论上讲,该数据将是对API的提取调用,例如,它是“ getTestVariable”,需要等待一段时间...

class Api {
  getLocation = async () => {
    var response = await this.getTestVariale();
    console.log(response);
    return response;
  }


  getTestVariale = () =>{
    setTimeout(function(){
      console.log("timeout done...");
      return "this is the test variable";
    },2000);
  }
 }

但是,1)console.log(response)给出了“ undefined”,因为它没有等待...并且2)回到主js api_data时,它是一些Promise对象,而不是变量response

2 个答案:

答案 0 :(得分:0)

如上面的注释所述,setTimeout没有返回Promise,因此getTestVariable没有返回值。

以下是代码的略微修改版本,有望将您带入正确的轨道:

class Api {
  getLocation = async () => {
    var response = await this.getTestVariale();
    console.log(response);
    return response;
  }


  getTestVariale = () => {
      return new Promise((resolve, reject) => {
          if (thereIsError)
              reject(Error('Error message'));
          else 
              resolve({foo: 'bar'});
      }
  }
}

如果我想进一步解释,请发表评论。

答案 1 :(得分:0)

getLocation中,您await的值来自this.getTestVariable。为了使此工作有效,this.getTestVariable 必须返回承诺;它可以通过两种方式完成-使getTestVariableasync函数或显式返回Promise。

由于您使用的是setTimeout(不是async函数),因此您必然会使用Promise。在这里,您去了:

class Api {
  async getLocation() {
    return await this.getTestVariable();
  }

  getTestVariable() {
    return new Promise((res, rej) => {
      setTimeout(() => res('test'), 2000)
    });
  }
}

async function main() {
  let api = new Api;

  console.log('Trying to get the location...');
  console.log('Voila, here it is: ', await api.getLocation());
}

main();

看起来很丑陋,但是如果使用set timeout,就无法实现它。

要点是getTestVariable的分辨率和要返回的值。

非常重要的一句话:您可以将getTestVariable标记为async函数,它会带来额外的Promise等级,但是您仍然会获得理想的结果。

相关问题