From 54ebed1db03f2f0b90e3bcd4091981064812d88f Mon Sep 17 00:00:00 2001 From: Alex Hultman Date: Fri, 8 Feb 2019 21:42:31 +0100 Subject: [PATCH] Add async/await example --- examples/AsyncFunction.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 examples/AsyncFunction.js diff --git a/examples/AsyncFunction.js b/examples/AsyncFunction.js new file mode 100644 index 0000000..5456072 --- /dev/null +++ b/examples/AsyncFunction.js @@ -0,0 +1,33 @@ +/* SSL/non-SSL example with async/await functions */ + +async function someAsyncTask() { + return 'Hey wait for me!'; +} + +const uWS = require('../dist/uws.js'); +const port = 9001; + +const app = uWS./*SSL*/App({ + key_file_name: 'misc/key.pem', + cert_file_name: 'misc/cert.pem', + passphrase: '1234' +}).get('/*', async (res) => { + /* Can't return or yield from here without responding or attaching an abort handler */ + res.onAborted(() => { + res.aborted = true; + }); + + /* Awaiting will yield and effectively return to C++, so you need to have called onAborted */ + let r = await someAsyncTask(); + + /* If we were aborted, you cannot respond */ + if (!res.aborted) { + res.end(r); + } +}).listen(port, (token) => { + if (token) { + console.log('Listening to port ' + port); + } else { + console.log('Failed to listen to port ' + port); + } +});