Another solution is to execute code via the sequential executor nsynjs.
If the underlying function is promisified
nsynjs will evaluate all promises sequentially, and put the promise result into the data property:
function synchronousCode() { var getURL = function(url) { return window.fetch(url).data.text().data; }; var url = 'https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js'; console.log('received bytes:',getURL(url).length);};nsynjs.run(synchronousCode,{},function(){ console.log('synchronousCode done');});<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>If the underlying function is not promisified
Step 1. Wrap the function with a callback into the nsynjs-aware wrapper (if it has a promisified version, you can skip this step):
var ajaxGet = function (ctx,url) { var res = {}; var ex; $.ajax(url) .done(function (data) { res.data = data; }) .fail(function(e) { ex = e; }) .always(function() { ctx.resume(ex); }); return res;};ajaxGet.nsynjsHasCallback = true;Step 2. Put synchronous logic into function:
function process() { console.log('got data:', ajaxGet(nsynjsCtx, "data/file1.json").data);}Step 3. Run function in synchronous manner via nsynjs:
nsynjs.run(process,this,function () { console.log("synchronous function finished");});Nsynjs will evaluate all operators and expressions step-by-step, pausing execution in case if the result of some slow function is not ready.
More examples are here.