Bluebird - Promise.resolve不起作用但返回工作

时间:2017-04-21 01:06:24

标签: javascript node.js express promise bluebird

我有这个函数,它返回一个Promise

save(data) => {
    return mymongo.insert(data).then(
        (result) => { 
           console.log('hello mongo');
           console.log(result);
           return Promise.resolve(result); 
        }
    )
}

在我的路由器中我称之为该功能

app.post('/printers', (req, res, next) => {
    save(req.body).then(
        (result) => {
            console.log('hello') // is not called, nothing is printed
            console.log(result) // is not called
            res.send(result)
        }
    ).catch(res.send);
});

然后用curl我做了请求

curl -v -d '{ ... }' -X POST http://localhost:8080/printers

它非常快,看起来很好

*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> POST /printers HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.52.1
> Accept: */*
> Content-Length: 35
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 35 out of 35 bytes
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 2
< ETag: W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"
< Date: Fri, 21 Apr 2017 01:01:30 GMT
< Connection: keep-alive
< 
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact

所以没有超时但没有响应,在控制台中我只看到来自save()的日志

hello mongo
{ .... }

当我用return Promise.resolve(result)替换return result时,我收到服务器的响应并执行了console.log(result),我在控制台中看到了

hello mongo
{ .... }
hello
{ .... }

1 个答案:

答案 0 :(得分:0)

这可能是promong的mongodb实现的问题,因为insert(...).then回调中的返回值由该实现处理。我没有找到任何与Promise / A +兼容的参考,你的代码似乎证明它不是。

如果您关注的是使用您喜欢的Promise API(在您的情况下可能是蓝鸟),那么请在较早阶段进行转换,这样您就不依赖于mongodb的then实现:

save(data) => {
    return Promise.resolve(mymongo.insert(data)).then(
        (result) => { 
           console.log('hello mongo');
           console.log(result);
           return result;
        }
    )
}