A lightweight library to simplify asynchronous operations using function generators and yield keyword, which is an alternative for Async/Await keywords without having to use any Transpiler like babel. You could wrap the function generator inside this function like this:
varawaitify=require('awaitify');vargetUsers=awaitify(function*(){// a xhr request to load users listvarusers=yieldjQuery.get('/api/users');returnusers;});getUsers().then((users)=>{console.log(users);});// orvarusers=yieldgetUsers();console.log(users);which allows you await on a promise using yield keyword.
constmapList=function*(){constmappedUsersInfoList=yieldawaitify.map(usersList,function*(userObject){constuserInfo=yieldloadUserInfo(userObject._id);userInfo.baseData=userObject;returnuserInfo;});// You can have access to the new list of usersInfo}.awaitify();constloadData=function*(){const{ users, config }=yieldawaitify.parallel({users: function*(){constusers=yieldgetUsers();console.log(users);returnusers;},config: awaitify.fs.loadConfigFile('./package.json')});// You can have access to both users and config variable here}.awaitify();This library also allows the pass generator functions to the promise chain implemented by this module:
getUsers().then(function*(users){console.log(users);varuser=yieldjQuery.get('/api/users/5698d6a5246af3c847be3000');console.log(user);});varawaitify=require('awaitify');varfs=require('fs');varreadFile=path=>awaitify.cb(cb=>fs.readFile(path,'utf8',cb)));varmain=awaitify(function*(){vardata;try{data=yieldreadFile('/any/file/path');}catch(err){console.log(err,err.stack);}returndata;});main();// orreadFile('/any/file/path').then(data=>console.log(data)).catch(err=>console.log(err,err.stack))constSampleModuleV1=awaitify.module({*createSomething(){letresult=yieldPromise.resolve('Something');result+=' V1';returnresult;},});constSampleModuleV2=awaitify.module(SampleModuleV1,{*createSomething(){letresult=yieldSampleModuleV1.createSomething();result+=', V2';returnresult;},});constresult=yieldSampleModuleV2.createSomething();console.log(result);// "Something V1, V2"