Business Code request within request

Hi everyone, I’ve been trying to retrieve data from a request within a request. It seems that the first one declared is always returned but any subsequent requests do not even initiate. Quite new to js and not too sure if this is todo with cloud code or the nature of promises. Any help would be greatly appreciated.

return Backendless.Data.of('People').find( queryBuilder )
.then(result => {
    var names = result.map(a => a.personName)
    names.forEach(function(value) {
    var whereStatement = req.query.whereClause + " AND " + "personName = '" + value + "'"
    console.log("Search for " + value);
  
  var sumQueryBuilder = Backendless.DataQueryBuilder.create().setWhereClause(  req.query.whereClause );

  return Backendless.Data.of('post').find( sumQueryBuilder )
  .then(postResult => {
    console.log("post found")
  })
  .catch(err => {
    console.log("ERROR")
    return Promise.reject('Got an error : ' + err.message)
});

Thanks!

Hello @MattW

I would recommend you to use async/await which is supported in our Server Code, for that you need to mark the root function with the keyword async and then use await for all async functions.

Here is a simple example

async loadAllItems(){
   const people = await Backendless.Data.of('People').find( queryBuilder )

   const asyncRequests = people.map(person => {
      return Backendless.Data.of('post').find( sumQueryBuilder )
   }) 

   const posts = await Promise.all(asyncRequests)

   // do whatever you need with the posts objects

   return posts
}

Regards, Vlad

Hi Vladimir,

Thanks for your response, makes sense, however I get the following:

When calling
console.log(loadAllItems())
I get Promise <Pending> - which makes sense, but when calling

loadAllItems().then( result => {
console.log(result)
})

I get no response in the console.
Is this the correct way of handling the result?
Regards, Matt

it’s tough to say without context, it could be a few issues why you don’t see that result

  1. does this loadAllItems return result?
  2. does this loadAllItems keep the main sequence of async invocations?
  3. is there a return before calling the loadAllItems
  4. etc.

have you tried to use

const result = await loadAllItems()

take a look at this https://javascript.info/async-await

1 Like

I got it! I forgot to include the return before calling loadAllItems (mentioned in 3.). Very appreciative of your help, Vlad! Thank you!