【问题标题】:How to write asynchronous code for Node.js and express.js如何为 Node.js 和 express.js 编写异步代码
【发布时间】:2017-01-14 18:17:14
【问题描述】:

我正在尝试编写长池。

  • GET /task - 获取所有任务
  • POST /task - 添加带有正文 {"title":"content"} 的新任务
  • GET /task-new - 在 rxjs 订阅事件之后解析,以便我们可以获取所有任务 http://pokazywarka.pl/ybtufb/

代码:

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!')
});

我正在使用带有 db.json 的 json-server:

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

所以,代码很简单。我想在订阅 observable 事件后解决 Promise,但 express.js 阻塞线程并在 5000 毫秒后解决,并返回事件(应该在事件发生后更早解决)

【问题讨论】:

  • 请正确格式化您的代码块

标签: node.js rxjs


【解决方案1】:

在 new Promise(function (resolve, reject) {

之前使用 return

【讨论】:

    【解决方案2】:

    一切正常。我用邮递员测试过。因此,我在浏览器等待的情况下进行 GET,并使用 Postman 进行 POST,请求以正确的顺序解析。 (第一个 POST 第二个 GET)

    【讨论】:

      猜你喜欢
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      相关资源
      最近更新 更多