× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Doing actions after asynchronous calls in JavaScript

Jessamyn Smith
Jul 15, 2015
<p>Many actions you might take in JavaScript are asynchronous, meaning that they do not return immediately, but invoke a callback method when they are complete. This means that you can end up trying to run code using data that is not yet initialized.</p> <p>Promises are a clean way of working with asynchronous calls to ensure that subsequent processing happens only when a method is complete. The general idea is that inside your method (e.g. someMethod()), you create a promise, which you can reject if an error occurs, or resolve when all other processing is done. The caller can then invoke someMethod.then(), which takes a success callback method and an error callback method.</p> <p>Promise libraries exist for many JavaScript frameworks, including Angular (<a href="https://docs.angularjs.org/api/ng/service/%24q">$q</a>) and Node (e.g. <a href="https://www.npmjs.com/package/node-promise">node-promise</a>).</p>
comments powered by Disqus