gistlib
To wait for a function to finish its operation in JavaScript, there are several ways.
index.tsxfunction myFunction(callback) { // Some operation callback(); } myFunction(function() { console.log('Operation completed!'); }); 136 chars9 lines
function myFunction(callback) { // Some operation callback(); } myFunction(function() { console.log('Operation completed!'); });
index.tsxfunction myFunction() { return new Promise((resolve, reject) => { // Some operation if (/* operation successful */) { resolve('Operation completed!'); } else { reject('Operation failed!'); } }); } myFunction().then(result => { console.log(result); }).catch(error => { console.error(error); }); 331 chars17 lines
function myFunction() { return new Promise((resolve, reject) => { // Some operation if (/* operation successful */) { resolve('Operation completed!'); } else { reject('Operation failed!'); } }); } myFunction().then(result => { console.log(result); }).catch(error => { console.error(error); });
index.tsxasync function myFunction() { // Some operation let result = await someOtherFunction(); return result; } myFunction().then(result => { console.log(result); }).catch(error => { console.error(error); }); 213 chars12 lines
async function myFunction() { // Some operation let result = await someOtherFunction(); return result; } myFunction().then(result => { console.log(result); }).catch(error => { console.error(error); });
Note that async/await works only inside an async function.
gistlibby LogSnag