从 Promise Typescript 中取出一个值
Posted
技术标签:
【中文标题】从 Promise Typescript 中取出一个值【英文标题】:Get out a value from promise Typescript 【发布时间】:2018-07-27 11:41:51 【问题描述】:我需要为将来的请求获取 userKey(自动生成):
addItemToCollection(userMail,item)
let userKey;
firebase.database().ref('user-list').orderByChild('email').equalTo(userMail)
.once('value')
.then(snapshot =>
snapshot.forEach(function(child)
//userkey is the value that i want
userKey= child.key
);
);
//Outside the promise i need userkey Value.
this.collectionRef=this.db.list('user-list/'+userKey+'/collection/bouteille');
return this.collectionRef.push(item);
this.db 在我的承诺中找不到,为什么我今天在那里(我是 ionic 3 和 firebase 的新手)
【问题讨论】:
你不能从 Promise 同步获取值。await
可以以 看起来 同步的方式“解压”它,但这不是 Promise 的工作方式。
我并不想冒犯,我们都是曾经的学习者,但 firebase、ionic、Promises 和 typescript 本身都是复杂的主题。你需要学习 javascript(不是 TypeScript)和 html(不是 webcomponents)以及同步和异步代码之间的区别(以及 Promises 如何适应它)。了解数据库的工作原理。然后回到 ionic/TypeScript/Firebase/await。否则这些东西的文档只会让你感到困惑:他们会假设你知道你不知道的事情。
【参考方案1】:
使您的函数异步,并将 await 放在 firebase 调用之前。
【讨论】:
以上是关于从 Promise Typescript 中取出一个值的主要内容,如果未能解决你的问题,请参考以下文章
Typescript编译器无法从Promise resolve调用中推断类型
当我从等待移动到 Promise.all 时,TypeScript 函数返回类型错误