Error when adding new item to a collection in a for loop

Got an error " Operation (add) not allowed during save" while trying to add data to a dataset repeatedly in a for loop. This is a dummy code to simplify the original code. I just want to add 4 items to an empty collection and then, after save, build the string “0123”

$w . onReady (() => {
$w ( “#dataset1” ). onReady ( () => {
let str = ‘’ ;
for ( let i = 0 ; i <= 3 ; i ++){
$w ( “#dataset1” ). add (). then (() => {
$w ( “#dataset1” ). setFieldValue ( “title” , “New Title” );
// excpected to add 4 items named “New Title” to the “title” column on “dataset1”
$w ( “#dataset1” ). save (). then (() =>{
str = str + i; // expected output “0123”
});
});
}
});
});

I’d appreciate any help. Thanks.

Try:

let i = 0;
let str = '';
function addItem(){
return $w("#dataset1").add().then(() => {
 $w("#dataset1").setFieldValue("title", "New Title");
 return $w("#dataset1").save();
  })
  .then(() => {
       i++;
       str += i;
	if(i < 4){return addItem();}
      });     
}

$w.onReady(() => {
$w("#dataset1").onReady(addItem);
})

Works like a gem! You’re a life saver. Many thanks, J.D.!