Ich versuche, Long-Pooling zu schreiben.Wie schreibe ich asynchronen Code für Node.js und express.js
- GET
/task
- erhalten alle Aufgaben - POST
/task
- neue Aufgabe mit Körper hinzufügen{"title":"content"}
/task-new
GET - lösen nach rxjs Ereignis abonnieren, so dass wir alle Aufgaben bekommen http://pokazywarka.pl/ybtufb/
-Code :
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var request2 = require('request');
var Promise = require("bluebird");
var Rx = require('rx');
var RxNode = require('rx-node');
var source = Rx.Observable.return(42);
var emitter = RxNode.toEventEmitter(source, 'data');
app.get('/task', function (req, res) {
request2('http://localhost:3000/task', function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send(JSON.parse(body));
}
})
});
app.post('/task', jsonParser, function (req, res) {
// Ensure to call publish to fire events from the observable
emitter.publish();
request2.post({
url: 'http://localhost:3000/task',
headers: {'Content-Type': 'application/json'},
body: '{"title":"' + req.body.title + '"}'
},
function (error, response, body) {
res.send(req.body);
}
);
});
setTimeout(function() {
emitter.on('data', function (data) {
console.log('Data: ' + data);
});
},0);
app.get('/task-new', function (req, res) {
new Promise(function (resolve, reject) {
emitter.on('end', function() {
console.log('End');
resolve();
});
setTimeout(function() {
resolve();
console.log("1");
}, 5000);
}).then(function() {
res.send('nowe taski');
});
});
app.listen(2000, function() {
console.log('Example app listening on port 2000!')
});
Ich verwende Json-Server mit db.json:
{
"task": [
{
"id": 1,
"title": "task1"
},
{
"title": "task2",
"id": 2
}
]
}
So Code einfach ist. Ich will lösen, nachdem Versprechen beobachtbaren Ereignis abonnieren, aber Express.js Block Thread und lösen nach 5000 ms und gibt Ereignisse
pls formatieren Sie Ihren Code-Block richtig –