我试图检索给定documentID的文档字段值。我已经解决了db调用部分,但无法将数据发送回去。就好像下面的函数this.userDbService.getVendorNameFromUserId
根本没有被调用一样。
下面是父函数:
async getVendorName() {
let name;
//blindtiger not going here.
//calling to 'private userDbService: UserDbService'
name = await this.userDbService.getVendorNameFromUserId('2OD1yTnMrecMgqljvHFHDjug1VT2');
console.log(name);
return name.toString();}
下面是函数getVendorNameFromUserId(''):
async getVendorNameFromUserId(id: string): Promise<string> {
let vendorName = '';
const userCollectionRef = await doc(this.store, 'clients/' + id);
await docData(userCollectionRef, {idField: 'id'}).forEach(el => {
//correctly is 'blindtiger' from db call.
console.log(el['user'].companyName.toString())
return el['user'].companyName.toString();
});
//parent function doesn't yield any results - as if this is not called.
// It should yield 'blindtiger' here.
return 'NOT FOUND';
}
getVendorName()是在一个类型脚本文件的构造函数中调用的,这个函数结果的值将用于获取该供应商名称的所有产品。
constructor(private shopifyService: ShopifyService, private userDbService: UserDbService, private modalService: NgbModal, private userAuthService: UserAuthService, private itemDb: ItemDbService) {
let vendorName: string;
const name = this.getVendorName();
console.log(name);
this.getAllProducts(name).then(result => {
console.log(result);
this.itemsToSell = result;
});
}`
我有一种感觉,我错过了一些与异步相关的东西-- buy会喜欢任何关于为什么“blindtiger”的价值甚至没有被传递到链上的建议。
我尝试过在函数调用- getVendorNameFromUserId()中添加异步等待,如果我在docData()的from中删除了等待关键字:
await docData(userCollectionRef, {idField: 'id'}).forEach(el => {
//correctly is 'blindtiger' from db call.
console.log(el['user'].companyName.toString())
return el['user'].companyName.toString();
});`
我得到的结果是'NOT FOUND' --这意味着它正确地将数据向上传递。我认为调用函数没有等待这个函数是有问题的,看起来像这样:
async getVendorName() {
let name;
//blindtiger not going here.
//calling to 'private userDbService: UserDbService'
name = await this.userDbService.getVendorNameFromUserId('2OD1yTnMrecMgqljvHFHDjug1VT2');
console.log(name);
return name.toString();
}
docData返回一个可观察对象。
const data = await docData(userCollectionRef, {idField: 'id'}).pipe(take(1)).subscribe(user => {
vendorName = user['user'].companyName;
//does not yield blind tiger
console.log({dataDone: vendorName});
})
//does yield blind tiger
console.log({dataAfter: vendorName})
return vendorName['user'].companyName
}
2条答案
按热度按时间pw9qyyiw1#
我假设
docData()
返回一个数组,其中只需要第一个值,因为method-signature读取getVendorNameFromUserId
,而您只传递了一个id
,因此您的代码如下所示:请注意:您不需要在
getVendorName()
中写入toString()
,因为getVendorNameFromUserId()
已经返回了string
类型的承诺。pn9klfpd2#
你的前途是有回报的:它将返回foreach的结果,而不是
getVendorNameFromUserId
的结果。请改用常规forof