JavaScript: Difference between revisions
No edit summary |
|||
Line 90: | Line 90: | ||
} | } | ||
} | } | ||
</syntaxhighlight> | |||
==Promises== | |||
See [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise Promises]<br> | |||
In general, a function returns a promise if it needs to perform asyncronous tasks.<br> | |||
<syntaxhighlight lang="javascript"> | |||
function myFunc() { | |||
// Do syncronous things here | |||
return new Promise((resolve, reject) => { | |||
// Do asyncronous things here | |||
// Return data | |||
resolve(myData); | |||
// Or if we have an error | |||
reject(myError); | |||
}); | |||
} | |||
myFunc() | |||
.then(data => { | |||
console.log(data); | |||
}).catch(err => { | |||
console.error(err); | |||
}); | |||
</syntaxhighlight> | </syntaxhighlight> | ||