Roll20 uses cookies to improve your experience on our site. Cookies enable you to enjoy certain features, social sharing functionality, and tailor message and display ads to your interests on our site and others. They also help us understand how our site is being used. By continuing to use our site, you consent to our use of cookies. Update your cookie preferences .
×

Extract Roll Result from sendChat callback

Hey all, I'm working with something that I'm sure is simple but, despite 2 hours of Googling, I can't find a solution.  I'm working with an API to roll an attack and all I want to do is save the result of the roll outside of the callback function.  I have: sendChat('', txt, function(ops) //txt is the inline dice roll (ex. [[1d20+8]]) {                        rollResult = ops[0].inlinerolls[0].results.total;                        log(rollResult); } and I want to use the value of rollResult outside  of the callback.  The fact that sendChat is asynchronous seems to be what's killing me.  I've tried adding sleep methods, re-scoping the rollResult variable, scouring StackOverflow and this forum, and still can't find any way to get that value out of the callback and back into my "main script".
1582654055

Edited 1582654607
Scott C.
Forum Champion
Sheet Author
API Scripter
Compendium Curator
You'll need to use async/await and promises to accomplish this. Together, these two features of JS allow you to write asynchronous code as if it were synchronous. Try this: var attackRoller = async function(txt){     let rollResult = await new Promise((resolve,reject)=>{     sendChat('',txt,(ops)=>{     resolve(ops[0].inlinerolls[0].results.total);     });     });     log(rollResult); }; EDIT: Note that you can return rollResult to other functions if you make them async as well, or use it to call future functions. Something like the below for returning the result: var attackRoller = async function(txt){     return new Promise((resolve,reject)=>{     sendChat('',txt,(ops)=>{     resolve(ops[0].inlinerolls[0].results.total);     });     }); }, resolveAttack = async function(msg_orig){ let msg = _.clone(msg_orig), defense,dice; if(!/^!attack /.test(msg.content)){ return; } msg.content.replace(/!attack defense:(\d+) dice:(\d+d\d+)/,(match,def,die)=>{ defense = def*1; dice = die; }); let result = await attackRoller(`[[${dice}]]`); sendChat('',`Your total damage done was ${result*1 - defense}`); }; on('chat:message',resolveAttack);