What I am trying to do is to attach a payload to the tangle using MAM protocol. If I run this loop for k=5 times it works fine i.e., data is attached to the Tangle. I confirmed that the data is attached by writing fetching code as well and it works fine. However, when I try to increase loop counter greater than 5 it gives me an error "Failed to attach message". I want to know what's wrong in the code. I have used different test nodes as well to make it work but it's not working.
var now = require("performancenow")
const math = require('mathjs')
const Mam = require('./lib/mam.client.js')
const { asciiToTrytes, trytesToAscii } = require('@iota/converter')
const IOTA = require('iota.lib.js')
const iota = new IOTA({
provider: 'https://dyn.tangle-nodes.com:443'
})
var k;
for (k = 0; k <200; k++){
//seed generator
const generate = require('iota-generate-seed');
seed = generate();
//key
const key='mysecret'
//Channel mode
const type = 'restricted'
// Initialise MAM State
let mamState = Mam.init(iota, seed, 2)
// Set channel mode
mamState = Mam.changeMode(mamState, type, key)
// Callback used to pass data out of the fetch
const logData = data => console.log(JSON.parse(trytesToAscii(data)))
const publish = async (packet, i) => {
// Create MAM Payload - STRING OF TRYTES
const trytes = iota.utils.toTrytes(JSON.stringify(packet))
const message = Mam.create(mamState, trytes)
// Save new mamState
mamState = message.state
// Attach the payload.
await Mam.attach(message.payload, message.address)
const logData = trytes => console.log(JSON.parse(iota.utils.fromTrytes(trytes)))
console.log("Payload: "+packet, "Payload in trytes: "+ asciiToTrytes(packet))
} //end of async
publish('0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789', k)
}//end of k loop