I have this function which returns a Promise
save(data) => {
return mymongo.insert(data).then(
(result) => {
console.log('hello mongo');
console.log(result);
return Promise.resolve(result);
}
)
}
in my router I call that function
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);
});
then with curl I do the request
curl -v -d '{ ... }' -X POST http://localhost:8080/printers
It is pretty fast and looks fine
* 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
so no timeout but no response and in console I see only the logs from save()
hello mongo
{ .... }
when I replace return Promise.resolve(result)
with return result
then I receive the response from the server and console.log(result)
gets executed and in my console I see
hello mongo
{ .... }
hello
{ .... }
This may be a problem with the mongodb implementation of promises, since the return value in the insert(...).then
callback is treated by that implementation. I don't find any reference that it is Promise/A+ compliant, and your code seems to prove it is not.
If your concern is to use the Promise API of your liking (probably bluebird in your case), then do the conversion at an earlier stage, so you are not dependent on mongodb's then
implementation:
save(data) => {
return Promise.resolve(mymongo.insert(data)).then(
(result) => {
console.log('hello mongo');
console.log(result);
return result;
}
)
}