Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One should avoid the pyramid of doom:</p> <pre class="lang-js prettyprint-override"><code>var express = require('express'); var Q = require('Q'); var app = express(); app.get('/',function(req,res){ var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : '' }); connection.connect(); function doQuery1(){ var defered = Q.defer(); connection.query('SELECT 1 AS solution',defered.makeNodeResolver()); return defered.promise; } function doQuery2(){ var defered = Q.defer(); connection.query('SELECT 2 AS solution',defered.makeNodeResolver()); return defered.promise; } Q.all([doQuery1(),doQuery2()]).then(function(results){ res.send(JSON.stringify(results[0][0][0].solution+results[1][0][0].solution)); // Hint : your third query would go here }); connection.end(); }); app.listen(80); console.log('Listening on port 80'); </code></pre> <p>This sample show a result which depend of 2 independent computed values. Each of these values a queried in doQuery1 and doQuery2. They are executed in sequence, but asynchronously.</p> <p>Next you can see <code>Q.all(...</code> which basically call the "then" callback on success. Within that callback, the calculation is done.</p> <p>Using promises (details : <a href="https://github.com/kriskowal/q/blob/master/README.md" rel="noreferrer">Github Q: promise for Javascript</a> and <a href="http://en.wikipedia.org/wiki/Promise_(programming)" rel="noreferrer">wikipedia</a> ) permit to make your code cleaner, separate computation and handling of results and move things arround.</p> <p>Look at how easy it would be to add "doQuery3" as prerequisit for your calculation !</p> <p>And bellow the "package.json" bellonging to the sample code:</p> <pre class="lang-js prettyprint-override"><code>{ "name": "hello-world", "description": "hello world test app", "version": "0.0.1", "private": true, "dependencies": { "express": "3.2.0", "q": "0.9.3", "mysql":"2.0.0-alpha7" } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload