简体   繁体   English

如何使用Bluebird推广NodeJS Express

[英]How to promisify NodeJS Express with Bluebird

I'm using NodeJS with Express and using Bluebird for promises. 我在Express上使用NodeJS,并在Bluebird中使用了Promise。 I'm trying to promisify app object as below but once promisified functions always throw errors. 我正在尝试使应用对象如下所示,但是一旦承诺的功能总会引发错误。 Part of the code is below: 部分代码如下:

var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    Promise = require("bluebird");

    app.postAsync = Promise.promisify(app.post);

    app.postAsync('/api/v1/users/update').then(function(req, res, next) {
    // never gets here
    })
        .catch(function(err) {
            console.log("doh!!!"); 
        });

I tried to promisifyAll with same effect. 我试图以相同的效果promisifyAll。 Why is it failing and is there any way to promisify post/get? 为什么会失败,并且有什么方法可以保证发布/获取?

You really really don't want to do this. 您确实真的不想这样做。 A promise is the wrong abstraction for this. 承诺是对此的错误抽象。

A promise represents the outcome of one eventual operation. 一个承诺代表一个最终操作的结果。 A promise can only change its state once so even if you manage to promisify app.post correctly it will only be able to serve one client, once. 一个Promise只能更改一次状态因此即使您成功承诺了app.post的承诺,也只能一次为一个客户提供服务。

Promises are an awesome abstraction - but this is definitely not a problem promises aim to solve. 承诺是一个了不起的抽象-但这绝对不是承诺要解决的问题。 Instead, if you're interested in interesting abstractions with promises you can check kriskowal's (Q author) Q-IO or one of the promise routers where you return promises to respond but the handler itself is called multiple times. 相反,如果您对带有承诺的有趣抽象感兴趣,则可以检查kriskowal(Q作者)的Q-IO或返回承诺以响应的承诺路由器之一,但是处理程序本身被多次调用。

I cannot emphasize this enough - promises are an awesome abstraction but they do not solve or attempt to solve all your concurrency issues. 我不能足够强调这一点-Promise是一个很棒的抽象,但是它们不能解决或尝试解决所有并发问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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