我正在尝试在composer中创建一个简单的超级链接代码,它接受一个贷款编号,如果存在,则更新与之相关的资产,然后创建一个新资产。
我的模型文件如下所示:
asset Loan identified by loanNum{
o String loanNum
o Double balance
}
transaction createTransaction {
o String loanNum
o Double transAmount
}
我的脚本如下所示:
function createTransaction(tx) {
var NS = 'org.acme.ra';
var factory = getFactory();
var loanToUpdate
//returns all assets
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry){
return assetRegistry.exists(tx.loanNum);
})
.then(function(exists){
if (exists) {
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry2){
loanToUpdate = assetRegistry2.get(tx.loanNum)
loanToUpdate.balance = tx.transAmount;
return assetRegistry2
})
.then(function(updateAssetRegistry){
return updateAssetRegistry.update(loanToUpdate)//broken right here
})
}
else {
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry2){
var newLoan =factory.newResource(NS,'Loan',tx.loanNum);
newLoan.balance = tx.transAmount;
return assetRegistry2.add(newLoan);
})
}
})
}
脚本摘要:
当bool为False时,脚本正常工作并创建新资产,但当bool为True并且事务包含已存在的贷款编号时,我收到错误“错误:预期资源或概念。”
修改
现在我已经获得了更多这方面的经验,我认为通过内置关系可以更轻松地完成这项任务,但是在下面更新我的更新功能代码后会感觉不舒服。
使用修复更新了代码:
function createTransaction(tx) {
var NS = 'org.acme.ra';
var factory = getFactory();
var loanToUpdate
//returns all assets
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry){
return assetRegistry.exists(tx.loanNum);
})
.then(function(exists){
if (exists) {
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry2){
return assetRegistry2.get(tx.loanNum);
})
.then(function(updateloan){
loanToUpdate = updateloan
loanToUpdate.balance = tx.transAmount;
return getAssetRegistry(NS + '.Loan')
})
.then(function(assetRegistry3){
return assetRegistry3.update(loanToUpdate);
})
}
else {
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry2){
var newLoan = factory.newResource(NS,'Loan',tx.loanNum);
newLoan.balance = tx.transAmount;
return assetRegistry2.add(newLoan);
})
}
})
}
答案 0 :(得分:3)
获取资产注册表返回一个承诺,所以该行
loanToUpdate = assetRegistry2.get(tx.loanNum)
需要成为promise链的一部分,因此在更新之前需要.then
块来处理返回的值。