As you are thinking more about your Web page being an app, you look for ways to reduce the complexity by using modules. In earlier post Getting Started with Modules Using RequireJS , you learned how RequireJS provides a great way to think of your app in modules and to asynchronously load and run your app.
RequireJS helps your describe the dependencies of a module and make sure you load them before executing your script.
But what happens when your module is long running? You can certainly turn that portion into a module and the require the completion before continuing. But in my case, I want think about my AMD module as an object and then call long-running methods on that module after it has been loaded.
When you make an asynchronous call, you can use a promise to handle both successful completion of the work and potential errors that may arise during execution. Upon the successful completion of one asynchronous call, you may want to pass the result to make another request.
The solution combines the promises of Q.js with the Asynchronous Module Definition (AMD) of Require.JS.
Get Q and RequireJS from their websites or through NuGet in your Visual Studio project.
In this application, you will need:
- HTML file
- Scripts folder with two files: q.js and require.js
- Scripts/app folder with files: main.js and sampleQ.js
In the first step, create an HTML page that loads require.js and starts the main.js file.
You’ll come back to main.js to call your module in a later step.
Create Your Module
Create a module in Scripts/app/sampleQ.js. Define your module. In this case, you’ll define it as a function. In the example, you canuse the CommonJS syntax. If there are a lot of requirements, this syntax can be used to help you not get the parameters confused.
Then create a private method that returns a promise using Q’s deferreds.. If successful, it uses the Q’s resolve method. If unsuccessful, it uses Q’s reject method.
Finally, the module returns the methods that are publicly accessible.
Now I can call the count method in the module.
Calling the Module Using Promises
Now you can call into the module, which requires the module and q and any other libraries needed by the module. You can then call the publicly accessible methods. When they return a promise, you can handle the results for success or errors.
Sample code for this post is available in the DevDays GitHub repository at: https://github.com/devdays/single-page-app/tree/master/LoadTemplates
See the samples at 4a-RequirePlusQTest.html, Scripts/app/SampleQ.js, and Scripts/app/samplemain.js.
- Q.js documentation on GitHub