我正在使用node.js编写链码,我想要获得药品供应链中的药品历史。我部署了链码,调用了制造和购买合同,将药物的当前状态从一个所有者修改为另一个所有者。实际上,我只是为此修改了商业票据链码。所有者的更改反映在couchdb数据库中。但是当我试图通过药物键来获取药物的历史记录时,它并不能像预期的那样工作。
我使用的代码
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 }
如何做到这一点呢?我在这里做错了什么?请帮帮我。
发布于 2020-11-10 19:35:26
函数
ctx.stub.getHistoryForKey(drugKey);
是一个异步函数。因此您需要添加等待的
const promiseOfIterator = await this.ctx.stub.getHistoryForKey(drugKey);
然后,您可以遍历结果。
发布于 2020-11-11 17:19:02
我在一个演示中做到了这一点:
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
}
}
有关Javascript中迭代器的更多信息,请查看Mozilla文档。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
https://stackoverflow.com/questions/64762803
复制相似问题