Promise 返回 undefined 和 status pending
Posted
技术标签:
【中文标题】Promise 返回 undefined 和 status pending【英文标题】:Promise returning undefined and status pending 【发布时间】:2019-07-16 15:59:22 【问题描述】:我正在向 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。
【参考方案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()
方法后不需要返回值;
【讨论】:
以上是关于Promise 返回 undefined 和 status pending的主要内容,如果未能解决你的问题,请参考以下文章
在异步函数内部,从回调函数返回值返回 Promise(undefined) [重复]
在异步函数内部,从回调函数返回值返回 Promise(undefined) [重复]
即使使用 Await,Promise 也会不断返回 Undefined