website/docs/examples/promise-wrapper/co-await.mdx
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';
'use strict';
const mysql = require('mysql2/promise');
async function test() {
const c = await mysql.createConnection({
port: 3306,
user: 'testuser',
namedPlaceholders: true,
password: 'testpassword',
});
console.log('connected!');
const [rows, fields] = await c.query('show databases');
console.log(rows);
try {
const [rows, fields] = await c.query('some invalid sql here');
} catch (e) {
console.log('caught exception!', e);
}
console.log(await c.execute('select sleep(0.5)'));
console.log('after first sleep');
console.log(await c.execute('select sleep(0.5)'));
console.log('after second sleep');
let start = +new Date();
console.log(
await Promise.all([
c.execute('select sleep(2.5)'),
c.execute('select sleep(2.5)'),
])
);
console.log(
'after 2+3 parallel sleep which is in fact not parallel because commands are queued per connection'
);
let end = +new Date();
console.log(end - start);
await c.end();
const p = mysql.createPool({
port: 3306,
user: 'testuser',
namedPlaceholders: true,
password: 'testpassword',
});
console.log(await p.execute('select sleep(0.5)'));
console.log('after first pool sleep');
start = +new Date();
console.log(
await Promise.all([
p.execute('select sleep(2.5)'),
p.execute('select sleep(2.5)'),
])
);
console.log('after 2+3 parallel pool sleep');
end = +new Date();
console.log(end - start);
await p.end();
}
test()
.then(() => {
console.log('done');
})
.catch((err) => {
console.log('error!', err);
throw err;
});
'use strict';
const mysql = require('mysql2/promise');
const co = require('co');
co(function* () {
const c = yield mysql.createConnection({
port: 3306,
user: 'root',
namedPlaceholders: true,
});
const rows = yield c.query('show databases');
console.log(rows);
console.log(yield c.execute('select 1+:toAdd as qqq', { toAdd: 10 }));
yield c.end();
})
.then(function () {
console.log('done');
})
.catch(function (err) {
console.log(err);
throw err;
});
{
"plugins": ["transform-async-to-generator"]
}
{
"name": "promise-co-await",
"version": "1.0.0",
"description": "",
"main": "await.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.9.0"
}
}