承诺返回未定义状态

时间:2019-02-22 14:19:15

标签: javascript angularjs web-applications

我在Angular App中添加了一些功能,这就是问题:我试图使用创建可从服务器获取数据的Promise的函数,但是每次我尝试使用它时,它都返回未定义。我已经用console.log“调试”了我的变量,并将函数的结果作为值打印出来,并打印了 Promise {'pending'}

这是promise和我要分配的变量的功能。

all_allies(text = ''){
return new Promise((resolve, reject) => {
  const _text = text ? /${text} : ''
  const path = `${this.env.apiPath}/all_allies${_text}`

  this.$http
    .get(path)
    .then(response => {
      const { data } = response
      resolve(data)
      return data;
    })
    .catch(error  => reject(error))
})

变量

let allies = this.AliadosFactory.all_allies();

如您所见,函数和变量位于不同的脚本中。

我尝试使用等待保留字,但仍然无法正常工作

2 个答案:

答案 0 :(得分:0)

可以尝试这种方法吗?

let allies = await this.AliadosFactory.all_allies();
console.log(allies);

还是这样?

this.AliadosFactory.all_allies().then(allies => console.log(allies);

我确定它应该可以工作, 希望这会有所帮助。

祝您有美好的一天:)

答案 1 :(得分:0)

那是因为当您执行分配时,承诺尚未解决/被拒绝。

有两种简单的解决方案:

1。使用then()

this.AliadosFactory.all_allies()。then(result => console.log(result));

2。使用异步/等待

(请注意,您的类中需要一个异步方法)

async foo() {
let allies = await this.AliadosFactory.all_allies();
console.log(allies);
}

all_allies()中,您也不需要在调用resolve()方法后返回值;