Created
January 8, 2020 20:39
-
-
Save meriturva/bb47c62a02eb4b9c99bb0f79d82abcf5 to your computer and use it in GitHub Desktop.
Esempio di chiamate asincrone con ExpressJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var app = express(); | |
// Solo un semplice metodo di test | |
app.get('/', (req, res) => { | |
res.send('Hello World!'); | |
}); | |
// Qui faccio la send dentro alla then | |
app.get('/test1', (req, res) => { | |
verifyDelayed(2000).then((result) => { | |
res.send('Hello World! Random: ' + result); | |
}) | |
}); | |
// Qui utilizzo async/await | |
app.get('/test2', async (req, res) => { | |
const result = await verifyDelayed(2000); | |
res.send('Hello World! Random: ' + result); | |
}); | |
app.listen(3000, function () { | |
console.log('Example app listening on port 3000!'); | |
}); | |
// Solo una funzione che simula qualcosa di asincrono come la select su db | |
function verifyDelayed(t, v) { | |
return new Promise(function (resolve) { | |
setTimeout(resolve.bind(null, v), t) | |
}).then(() => { | |
return Math.random(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment