I am trying to get the index and created date of an entry knowing the created date of the one just before it.

I am trying to get the index and created date of an entry knowing the created date of the one just before it.

$w("#dataset1").onReady(() => {
$w("#dataset2").onReady(() => {

$w("#dataset1").setFilter(wixData.filter()
.gt("_createdDate", dateOfPriorEntry))
.then(() => {
let neededIndex=($w("#dataset1").getTotalCount()) -1
$w("#dataset2").getItems(neededIndex,1)
.then((results) = > {
let needeCreatedDate = results.items[0]._createdDate
})
.catch( (err) => {
  console.log(err);
} );
.catch( (err) => {
  console.log(err);
} );
})
})

This does not work on page ready and sparingly works when button is clicked, please is there another way of achieving this or what am I doing wrong here?