问题描述
我正在使用node.js编写chaincode,我想获取药品供应链中的药品历史。我部署了chaincode,调用了制造和购买合同,从而将药物的当前状态从一个所有者更改为另一个所有者。实际上,我为此修改了商业票据链码。所有者的更改反映在ouchdb数据库中。但是,当我尝试通过药物密钥获取药物历史记录时,却无法按预期进行。
我使用的代码
const promiSEOfIterator = this.ctx.stub.getHistoryForKey(drugKey);
const results = [];
for await (const keyMod of promiSEOfIterator) {
const resp = {
timestamp: keyMod.timestamp,txid: keyMod.tx_id
}
if (keyMod.is_delete) {
resp.data = 'KEY DELETED';
} else {
resp.data = keyMod.value.toString('utf8');
}
results.push(resp);
}
return results;
当我打印结果时,它给出:[]
当我这样做时:Drug.fromBuffer(getDrugHistoryResponse);
并将其打印出来,它将得到Drug { class: 'org.medicochainnet.drug',key: ':',currentState: null }
如何进行这项工作?我在这里做错了什么?请帮助我。
解决方法
功能
ctx.stub.getHistoryForKey(drugKey);
是一个异步函数。因此,您需要添加等待
const promiseOfIterator = await this.ctx.stub.getHistoryForKey(drugKey);
然后您可以遍历结果。
,我已经在这样的演示中做到了:
const promiseOfIterator = await this.ctx.stub.getHistoryForKey(drugKey);
const results = [];
while(true){
let res = await promiseOfIterator.next();
//In the loop you have to check if the iterator has values or if its done
if(res.value){do your actions}
if(res.done){
// close the iterator
await promiseOfIterator.close()
// exit the loop
return results
}
}
查看Mozilla文档以获取有关Java迭代器的更多信息。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators