【问题标题】:pending promise coming using async await in typescript在打字稿中使用异步等待来等待承诺
【发布时间】:2019-03-18 08:26:50
【问题描述】:

当我从 show 调用 loadhtml 方法时。我总是得到一个未决的承诺。我如何在没有回电的情况下获得价值。请在下面找到代码片段。

   async loadhtml(url: string) {
            var data =$.get(url).then(response=>{
                console.log("response=>",response)
                return response
            });
            return await data
        }

 show() {
      var data = this.loadhtml(require("../../template/template1.tpl"));
       console.log("html content=> ",data);
} 

【问题讨论】:

标签: typescript promise


【解决方案1】:

你可以将它包装在一个 Promise 中并返回,这样你就可以使用 await 在调用函数中等待它。

async loadhtml(url: string) {
  return new Promise((resolve, reject) => {
    $.get(url).then( response => {
      console.log("response=>",response)
      resolve(response)
    });
  });
}

async show() {
  var data = await this.loadhtml(require("../../template/template1.tpl"));
  console.log("html content=> ",data);
} 

【讨论】:

  • 将异步函数包装在一个 Promise 中是没有意义的,因为它已经返回了一个 Promise。 并且 $.get 已经返回了一个promise,所以你有一个promise 包装在一个promise 中包装在一个promise 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2017-06-15
  • 1970-01-01
  • 2018-02-03
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多