Am trying to create a batch of items(units). I want a user to indicate the number of units they want in a batch then the transaction creates the batch first then creates the number of units required. This is my code:
async function createBatch(batchTx) {
// get a code from the generator
let now = new Date();
let tokenData = {
brand: batchTx.brand,
unitCount: batchTx.unitCount,
created: now,
expiry: batchTx.expiryDate
}
let code = _generate_code(tokenData, 'Batch');
// create a new Batch token and add it to the registry
let factory = getFactory();
let token = factory.newResource('org.myOrganization', 'Token', String(code));
token.created = now;
token.updated = now;
let tokenAssetRegistry = await getAssetRegistry('org.myOrganization.Token');
await tokenAssetRegistry.add(token);
// create a batch using the token and code created above
let batch = factory.newResource('org.myOrganization', 'Batch', token.code);
batch.brand = batchTx.brand;
batch.expiryDate = batchTx.expiryDate;
batch.token = token;
batch.owner = batchTx.owner;
batch.created = now;
batch.updated = now;
let batchAssetRegistry = await getAssetRegistry('org.myOrganization.Batch');
await batchAssetRegistry.add(batch);
// update token with new batch
let tokenAssetRegistry1 = await getAssetRegistry('org.myOrganization.Token');
token.batch = batch;
tokenAssetRegistry1.update(token);
// CREATE UNITS
// get a code from the generator
let i;
for(i=0; i < batchTx.unitCount; i++) {
let unitTokenData = {
batch: batch,
created: now
};
let unitCode = _generate_code(unitTokenData, 'Unit');
// create a new Unit token and add it to the registry
let unitToken = factory.newResource('org.myOrganization', 'Token', String(unitCode));
unitToken.created = now;
unitToken.updated = now;
let tokenAssetRegistry2 = await getAssetRegistry('org.myOrganization.Token');
await tokenAssetRegistry2.add(unitToken);
// create units
let unit = factory.newResource('org.myOrganization', 'Unit', String(unitToken.code));
unit.batch = batch;
unit.token = unitToken;
unit.owner = batchTx.owner;
unit.created = now;
unit.updated = now;
let unitAssetRegistry = await getAssetRegistry('org.myOrganization.Unit');
await unitAssetRegistry.add(unit);
}
}
The problem is that the batch is created okay but when it comes to units, instead of creating 3 units if batchTx.unitCount
was 3, it only creates one. Is there anything am getting wrong about how composer works, or maybe some of my promise resolution is wrong? Any help in solving this will be much appreciated