【问题标题】:Bluebird - Promise.resolve doesn't work but return worksBluebird - Promise.resolve 不起作用但返回有效
【发布时间】:2017-04-21 01:06:24
【问题描述】:

我有一个返回 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
{ .... }

【问题讨论】:

  • 好吧return Promise.resolve(result); 通常是多余的,但如果result 是其他一些(在你的情况下不是蓝鸟)thenable 它会有所作为 - 但result 在你的情况不是thenable - 你能在你使用它的地方试试console.log(Promise.resolve.toString()),看看它是否输出类似function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }
  • 另外,尝试在您的.catch 中添加一些日志记录 - 也许会有一个对您有用的错误
  • return Promise.resolve(result); 不是必需的。只需执行return result;,只要我认为,您的 mongo 实现存在问题,而不是除了我提到的代码之外的代码。

标签: javascript node.js express promise bluebird


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2018-10-02
    • 2016-02-10
    • 2012-09-30
    相关资源
    最近更新 更多