-
Notifications
You must be signed in to change notification settings - Fork 3
/
awaitajax.js
114 lines (93 loc) · 2.68 KB
/
awaitajax.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* Created by techmaster on 2/11/17.
*/
const express = require('express');
const app = express();
const nunjucks = require('nunjucks');
const bodyParser = require("body-parser");
const plotly = require('plotly')('minhcuong', 'QxyhzCyCkE9Q3eOBlnFx');
const fs = require('fs');
const math = require('./math/hambac2');
const path = require('path');
const shortid = require('shortid');
const Promise = require('bluebird');
//Cấu hình nunjucks
nunjucks.configure('views', {
autoescape: true,
cache: false,
express: app,
watch: true
});
app.use('/public', express.static('public'));
// parse application/x-www-form-urlencoded
// for easier testing with Postman or plain HTML forms
app.use(bodyParser.urlencoded({
extended: true
}));
// Set Nunjucks as rendering engine for pages with .html suffix
app.engine('html', nunjucks.render);
app.set('view engine', 'html');
app.get('/', (req, res) => {
res.render('index3.html');
});
/***
* Hàm hứng post request sử dụng kỹ thuật async - await. Để chạy thử node --harmony-async-await asynawait.js
* app.post('/', async(req, res) => {...}
* filePath = await renderChart(a, b, c);
*/
app.post('/', async(req, res) => {
try {
[a, b, c] = math.validate_abc(req.body.a, req.body.b, req.body.c);
} catch (err) {
res.send(`validate_abc failed: ${err}`);
return;
}
try {
[x1, x2, filePath] = await renderChart(a, b, c);
res.json({'x1': x1, 'x2': x2, 'filePath': filePath}); //Trả về JSON
} catch (err) {
res.json({'error': `Error Render Chat: ${err}`});
}
});
app.listen(7000, () => {
console.log('Web app async-await AJAX listens at port 7000');
});
/***
* Logic tính toán và sinh ảnh đã được gói trong lời hứa trả về
* @param a
* @param b
* @param c
*/
function renderChart(a, b, c) {
return new Promise((resolve, reject) => {
let x_series, y_series, x1, x2;
try {
[x_series, y_series, x1, x2] = math.gendata(a, b, c);
} catch (err) {
reject(`math.gendata failed: ${err}`);
}
let trace = {
x: x_series,
y: y_series,
type: "scatter"
};
let figure = {'data': [trace]};
let imgOpts = {
format: 'png',
width: 1000,
height: 500
};
plotly.getImage(figure, imgOpts, function (error, imageStream) {
if (error) {
reject(`plotly.getImage failed: ${error}`);
}
let uniqueid = shortid.generate();
let filePath = `/public/${uniqueid}.png`;
let fullfilePath = __dirname.concat(filePath);
console.log(fullfilePath);
let fileStream = fs.createWriteStream(fullfilePath);
imageStream.pipe(fileStream);
resolve([x1, x2, filePath]);
});
});
}