【问题标题】:Promise returning undefined and status pendingPromise 返回 undefined 和 status pending
【发布时间】:2023-04-01 18:15:02
【问题描述】:

我正在向 Angular 应用程序添加一些函数,事情是这样的:我正在尝试使用一个函数来创建从服务器获取数据的承诺,但每次我尝试使用它时,它都会返回 undefined .我已经“调试”了 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();

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

我试过用await保留字还是不行

【问题讨论】:

  • 您应该在Network 选项卡中看到this.$http.get(..) 发起的请求发生了什么
  • @samb102 是的,我做到了,服务器响应是 200-OK。

标签: javascript angularjs web-applications


【解决方案1】:

你可以试试这个方法吗?

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

还是这样?

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

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

祝你有美好的一天:)

【讨论】:

  • 谢谢!我之前尝试过第一个选项,但没有成功,但第二个可以!现在,如何将结果分配给我之前创建的变量?
  • 你好尼克!你可以这样分配。 let var1; this.AliadosFactory.all_allies().then(allies => { var1 = allies; });
  • 你好 dalisoft!,不幸的是我刚刚尝试过,但它没有工作,在我分配变量后我打印它并打印undefined,也许还有另一种方法?我对 Web 应用有点陌生
  • Nick,它不会立即记录,因为 Promise 是异步微任务,我建议您谷歌 async/await in js 以更好地了解它的工作方式和原因/位置,希望这会有所帮助:)
【解决方案2】:

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

有两种简单的解决方案:

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()方法后不需要返回值;

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 2018-08-19
    • 2014-05-12
    • 2021-04-21
    • 2019-12-23
    • 2020-07-09
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多