简体   繁体   中英

How to write asynchronous code for Node.js and express.js

I'm trying to write long pooling.

  • GET /task - get all tasks
  • POST /task - add new task with body {"title":"content"}
  • GET /task-new - resolve after rxjs subscribe event so we can GET all tasks 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!')
});

I am using json-server with db.json:

{
    "task": [
        {
            "id": 1,
            "title": "task1"
        },
        {
            "title": "task2",
            "id": 2
        }
    ]
}

So, code is simple. I want resolve Promise after subscribe observable event but express.js block thread and resolve after 5000 ms, and returns events (should resolve earlier just after events)

在新的Promise(函数(解决,拒绝)之前使用return

Everything was ok. I tested with Postman. So I made GET with browser waiting and make POST with Postman, request resolve in correct order. (First POST second GET)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM