How to wrap async function calls into a sync function in Node.js or Javascript? How to wrap async function calls into a sync function in Node.js or Javascript? javascript javascript

How to wrap async function calls into a sync function in Node.js or Javascript?


deasync turns async function into sync, implemented with a blocking mechanism by calling Node.js event loop at JavaScript layer. As a result, deasync only blocks subsequent code from running without blocking entire thread, nor incuring busy wait. With this module, here is the answer to the jsFiddle challenge:

function AnticipatedSyncFunction(){  var ret;  setTimeout(function(){      ret = "hello";  },3000);  while(ret === undefined) {    require('deasync').runLoopOnce();  }  return ret;    }var output = AnticipatedSyncFunction();//expected: output=hello (after waiting for 3 sec)console.log("output="+output);//actual: output=hello (after waiting for 3 sec)

(disclaimer: I am the co-author of deasync. The module was created after posting this question and found no workable proposal.)


There is a npm sync module also. which is used for synchronize the process of executing the query.

When you want to run parallel queries in synchronous way then node restrict to do that because it never wait for response. and sync module is much perfect for that kind of solution.

Sample code

/*require sync module*/var Sync = require('sync');    app.get('/',function(req,res,next){      story.find().exec(function(err,data){        var sync_function_data = find_user.sync(null, {name: "sanjeev"});          res.send({story:data,user:sync_function_data});        });    });    /*****sync function defined here *******/    function find_user(req_json, callback) {        process.nextTick(function () {            users.find(req_json,function (err,data)            {                if (!err) {                    callback(null, data);                } else {                    callback(null, err);                }            });        });    }

reference link: https://www.npmjs.com/package/sync


You've got to use promises:

const asyncOperation = () => {    return new Promise((resolve, reject) => {        setTimeout(()=>{resolve("hi")}, 3000)    })}const asyncFunction = async () => {    return await asyncOperation();}const topDog = () => {    asyncFunction().then((res) => {        console.log(res);    });}

I like arrow function definitions more. But any string of the form "() => {...}" could also be written as "function () {...}"

So topDog is not async despite calling an async function.

enter image description here

EDIT: I realize a lot of the times you need to wrap an async function inside a sync function is inside a controller. For those situations, here's a party trick:

const getDemSweetDataz = (req, res) => {    (async () => {        try{            res.status(200).json(                await asyncOperation()            );        }        catch(e){            res.status(500).json(serviceResponse); //or whatever        }    })() //So we defined and immediately called this async function.}

Utilizing this with callbacks, you can do a wrap that doesn't use promises:

const asyncOperation = () => {    return new Promise((resolve, reject) => {        setTimeout(()=>{resolve("hi")}, 3000)    })}const asyncFunction = async (callback) => {    let res = await asyncOperation();    callback(res);}const topDog = () => {    let callback = (res) => {        console.log(res);    };    (async () => {        await asyncFunction(callback)    })()}

By applying this trick to an EventEmitter, you can get the same results. Define the EventEmitter's listener where I've defined the callback, and emit the event where I called the callback.