Toggle menu

synchronise

Allows asynchronous functions to be executed synchronously.

This library is distributed under the MIT license, its source is www.npmjs.com/package/synchronize (opens new window)

Executed

Server-side.

Details

var sync = require('synchronize');

iCM End Points execute synchronously. Each statement executes in order, with the next statement executing only after the current statement has completed. This causes problems when invoking libraries and methods which only have asynchronous interfaces. Asynchronous method calls return immediately, but the callback functions will be invoked at some point in the future after the asynchronous task is complete. Functions that rely upon the results of previous asynchronous calls are likely to fail because the End Point will have returned before the asynchronous operation completes its task and calls its callback.

The synchronise module has been provided to make asynchronous methods behave in a synchronous manner. It assumes that the callback uses node-style (err, result) callbacks. Functions are "wrapped" so that sync.await will not return until the function returned by sync.defer is called.

Example

function( params, credentials ) {
    var fs = require('n__fs'),
        sync = require('synchronize'),
        filePath = "worker.conf",
        result = null;
    
    try {
        // As endpoints are synchronous methods the following call to fs.stat will not work as the endpoint will return before fs.stat's callback is invoked.
        fs.stat(filePath, function(statsResult) {
            result = statsResult;
        });
        
        /* Any errors returned by the asynchronous call will be thrown as a normal exception that can be caught with a try/catch statement. Multiple and named arguments are supported with defers - see the synchronize module documentation for more information.
        1) sync.defer() returns a function that is passed as a callback into fs.stat
        2) sync.await() will not return until the function returned by sync.defer() (the callback) is called.
        3) The function returns the result of the call to result. */

        result = sync.await(fs.stat(filePath, sync.defer()));

    } catch (e) {
        result = e.message;
    }
    return result;
}

Last modified on 24 April 2023

Share this page

Facebook icon Twitter icon email icon

Print

print icon