Hi guys,

it took me a while to wrap my head around Promises and asynchronous processing in Node.js Apps. Especially the concept of await needed some learning from me.


So what's the deal ? If you really need to wait for the result of an asychronous call to come back, you have to return a Promise and resolve it. Otherwise, the await statement will not work as expected.


Here'e a sample:


async function operation() {
    return new Promise(function(resolve, reject) {
         var a = 0;
         var b = 1;
         a = a + b;
         a = 5; // may be a heavy db call or http request?
         resolve(a) // successfully fill promise
    })
}
async function app() {
    var a = await operation() // a is 5
}
app()


A similar construct can be used to make a call to a Domino app using domino-db which will return a promise and needs to be an async call anyways:


async function createDocumentsinDomino(accesstoken) {

  return new Promise(function (resolve, reject) {

  var back = '';

  const databaseConfig = {filePath: 'mynsf.nsf',}; // The database file name

  const createOptions = {

     documents: [

     {

      Form: 'Contact',

      FirstName: 'Heiko',

      LastName: 'Voigt',

      City: 'Shelburne',

      State: 'NS',

     },

     {

      Form: 'Contact',

      FirstName: 'Graham',

      LastName: 'Acres',

      City: 'Vancouver',

      State: 'BC',

     },

   ],

   accessToken: accesstoken,

};


/*

Now, let's add a document to a Notes Database as a user !

*/

useServer(serverConfig).then(async server => {

  const database = await server.useDatabase(databaseConfig);

  const response = await database.bulkCreateDocuments(createOptions);


  // Display the new document UNIDs

  const unids = response.documents.map(doc => doc['@unid']);

  console.log(`Documents created: ${unids}`);

  back = `Documents created: ${unids}`;

  }).catch(error => {

     console.log(error);

     back = { result: "ERROR", fields: null, error: error };

  });

  resolve(back);

}


Heiko.
Heiko Voigt   |   18 December 2019 13:24:53   |    NERD  domino-db  AppDevPack    |  
  |   Next Document   |   Previous Document

Discussion for this entry is now closed.

Comments (1)

Frank van der Linden       18.12.2019 18:09:33

Good explanation as it is very important in the current asynchronous world. Not only in the frontend, but also on the server with NodeJS and Reactive Java. Not waiting of if data is returned.