kyleamathews / superagent-bluebird-promise Goto Github PK
View Code? Open in Web Editor NEWAdd promise support to superagent using Bluebird
License: MIT License
Add promise support to superagent using Bluebird
License: MIT License
When updating to bluebird 3 the package breaks:
http://bluebirdjs.com/docs/new-in-bluebird-3.html
and
http://bluebirdjs.com/docs/api/cancellation.html
I don't have time to check it out further currently, just wanted to let you know.
I'm the creator of superagent-cache
and someone recently reported an issue to me saying that my 1.5.0
release breaks compatibility with this repo. I've created a branch to address the issue and asked the reporter to confirm it meets their needs.
However, I noticed that this repo does not allow a superagent instance to be passed into it. It appears that superagent-promise
, superagent-promise-plugin
, and my library all allow users to provide an existing superagent instance to be patched. With that in mind, are you open to optionally allowing users to pass in a superagent instance so that, for example, users can patch with my library and then patch with this library to get the bennefits of both?
As I said earlier, I have a branch I believe fixes the issue, but it's not a good fix--I believe this would be better.
Thanks!
With the following code, I have tired binding the context to this
:
rest.get('myUrl').then(function(res){
// do something with this
})
But regardless of how I do it, the function doesnt see this.anything. I have tired with function(){}.bind()
as well as rest.get('myUrl').bind().then()
.
edit: I also tried rest.get('myUrl').promise().bind().then()
.
Any ideas?
It appears you can't pass an object directly to Error
Hi,
on StackOverflow someone did not like to have to call .promise()
every time. You could make the request objects be thenables themselves, by introducing this simple additional helper method:
Request.prototype.then = function(onFulfilled, onRejected) {
return this.promise().then(onFulfilled, onRejected);
};
This code:
var api = 'http://localhost:3007/';
var promise = request.post(api + '/endpoint')
.send({
name: ' some data'
})
.promise();
return promise;
throws this error:
(intermediate value).cancellable is not a function
I have updated sails to v0.12.1, [email protected], [email protected] and using [email protected] adapter, [email protected]. For a promise like:
Model1.findOne().then(function (m1){
var condition
// some checks
if (condition === true){
Model1.update({}).then(function (m2){
return res.json(200, {updatedValue: m2[0]})
}).catch(function (error){
return res.json(400, {error: error.message})
})
}
}).catch(function (error){
return res.json(400, {error: error.message})
})
I am getting warning
Warning: a promise was created in a handler but was not returned from it
at [object Object].Deferred.toPromise (/home/vagrant/www/consumer-payments/node_modules/sails/node_modules/waterline/lib/waterline/query/deferred.js:494:61)
at [object Object].Deferred.then (/home/vagrant/www/consumer-payments/node_modules/sails/node_modules/waterline/lib/waterline/query/deferred.js:505:15)
at donePayload (/home/vagrant/www/consumer-payments/api/controllers/v1/PaymentController.js:265:18)
at /home/vagrant/www/consumer-payments/node_modules/sails/node_modules/async/lib/async.js:52:16
at /home/vagrant/www/consumer-payments/node_modules/sails/node_modules/async/lib/async.js:269:32
at /home/vagrant/www/consumer-payments/node_modules/sails/node_modules/async/lib/async.js:44:16
at /home/vagrant/www/consumer-payments/api/controllers/v1/PaymentController.js:228:22
From previous event:
at [object Object].Deferred.then (/home/vagrant/www/consumer-payments/node_modules/sails/node_modules/waterline/lib/waterline/query/deferred.js:505:27)
at Object.request (/home/vagrant/www/consumer-payments/api/controllers/v1/PaymentController.js:193:8)
at wrapper (/home/vagrant/www/consumer-payments/node_modules/lodash/index.js:3095:19)
at routeTargetFnWrapper (/home/vagrant/www/consumer-payments/node_modules/sails/lib/router/bind.js:179:5)
at callbacks (/home/vagrant/www/consumer-payments/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
at param (/home/vagrant/www/consumer-payments/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
at pass (/home/vagrant/www/consumer-payments/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
at nextRoute (/home/vagrant/www/consumer-payments/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
at callbacks (/home/vagrant/www/consumer-payments/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
at /home/vagrant/www/consumer-payments/node_modules/sails/lib/router/bind.js:187:7
at done (/home/vagrant/www/consumer-payments/api/policies/v1/isAuthorizedProduct.js:29:25)
at /home/vagrant/www/consumer-payments/api/services/authentication.js:22:22
at Object.calculateHash (/home/vagrant/www/consumer-payments/api/services/hashing.js:8:12)
at Object.wrapper [as calculateHash] (/home/vagrant/www/consumer-payments/node_modules/lodash/index.js:3095:19)
However, adding a return true at the end of first promise, does not give the warning.
Model1.findOne().then(function (m1){
var condition
// some checks
if (condition === true){
Model1.update({}).then(function (m2){
return res.json(200, {updatedValue: m2[0]})
}).catch(function (error){
return res.json(400, {error: error.message})
})
}
return true
}).catch(function (error){
return res.json(400, {error: error.message})
})
Is there any other possible way to suppress the warning?
Currently, the package.json requires superagent v2 in devDependencies
. However, in peerDependencies
, it requires superagent v1 or higher. This means that it will not require or install superagent v2 if v1 is installed. I'm running into compatibility issues with this library while using superagent v1, and it looks like this PR was intended to require superagent v2. Can the peerDependencies
be corrected to require superagent v2?
I'm using superagent-mocker
in my unit tests to mock out the super-agent responses, but it seems not to work for non-200 responses.
The following code ends up causing an error:
Uncaught TypeError: Cannot read property 'status' of null
if (typeof res !== "undefined" && res.status >= 400) {
var msg = 'cannot ' + req.method + ' ' + req.url + ' (' + res.status + ')'
From: https://github.com/KyleAMathews/superagent-bluebird-promise/blob/master/index.js#L66-L67
This is happening when superagent-mocker
calls that function with res
passed in as null
rather than undefined
.
https://github.com/A/superagent-mocker/blob/master/index.js#L99-L100
I'm not entirely sure which of your libraries is responsible for this bug, but either case looks like a pretty easy fix. (I'll submit an issue to superagent-mocker
as well)
If you want, I can submit a PR to change
if (typeof res !== "undefined" && res.status >= 400) {
to
if (res && res.status >= 400) {
Thanks for taking your time to contribute this very useful library to the OSS community!
Hey there,
this code that used to work for me before now does not.
request.get("http://www.myserver.com/test.json").then(function (req) {
console.log(req.body);
});
Not quite sure why, but it's apparently an issue:
Error
at Object.<anonymous> (/usr/lib/node_modules/cli/node_modules/superagent-bluebird-promise/index.js:16:36)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/usr/lib/node_modules/cli/lib/install.js:15:15)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at attemptRequire (/usr/lib/node_modules/cli/node_modules/attempt-require/index.js:6:20)
at Object.<anonymous> (/usr/lib/node_modules/cli/bin/cli.js:39:15)
I keep seeing this warning
Warning: a promise was rejected with a non-error: [object Object]
in the console when I make a request like below that results in an error (like a 500 status for example). The request works fine and I can catch the error no problem, but I'd like to get that warning to go away in the console. Any idea how?
let request = require('superagent-bluebird-promise')
request.post(url, data)
.promise()
.then((res) => {
console.log(res);
})
.catch((e) => {
console.log(e);
})
I need to do some 401 checking on every request to an API. There's a library to do this for vanilla superagent, https://github.com/codesuki/superagent-intercept, but the expectations are of course different for your library.
Is there a recommended way to implement something similar for this library?
Thanks.
Hi admin,
How to I could post json array object?
For example: ['hello','word']
Please give the idea ?
Hi, I just migrated from superagent
to this lib, and I found that for the parameter passed down to the error handler, superagent-bluebird-promise
passes different structured error object:
From superagent
:
From superagent-bluebird-promise
:
Any specific reason for the change? Otherwise, I think you should keep the signature consistent.
If I require bluebird and create a promise before require('superagent-bluebird-promise')
, I get the following error. Moving the require to the beginning of the entry point file or adding Promise.config({cancellation: true})
to the other instance of bluebird fixes the issue, but ideally wouldn't cancellation be configurable for superagent-bluebird-promise instead of mandatory? Threw together a PR for quick fix for now.
Unhandled rejection Error: cannot enable cancellation after promises are in use
at Function.Promise.config (/var/www/my_app/node_modules/bluebird/js/release/debuggability.js:162:19)
at Object.<anonymous> (/var/www/my_app/node_modules/superagent-bluebird-promise/index.js:9:9)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
I just came across this library. From the README.md, it was not clear to me what would be the advantages of using it over promisifying the superagent library directly:
var request = require('superagent');
var Promise = require('bluebird');
Promise.promisifyAll(request);
The only difference I can see is that I would have to use request.endSync() to get a promise back, which is not a great justification for adding one more dependency to my projects. Am I missing something really obvious?
Hi,
I have this request
return superagent.post(url)
.send(request)
.set("Content-Type", "application/ocsp-request")
.then(function(res){
return res;
}).catch(function(err) {
return err;
});
I get an error saying
TypeError: first argument must be a string or Buffer
I played around with parts and it seems the problem is when I set the content-type.
However, when I try to set other headers, it works fine. I was wondering if it's specific to content-type.
Thanks
Hey - just wondering why this doesn't use promisify
and uses the promise constructor instead.
I'm using your library to make a request to middleware and it is taking too long to respond. How to avoid the client to retry and i want it to wait forever till the backend respond.
Input:
git clone [email protected]:KyleAMathews/superagent-bluebird-promise.git
cd superagent-bluebird-promise
npm install
npm run test
Output:
✗ test/test.coffee
✗ #84: Line exceeds maximum allowed length. Length is 81, max is 80.
✗ Lint! » 1 error and 0 warnings in 1 file
-> running 1 suite
superagent-promise
should exist.. ok
should resolve a res object when the returned statusCode is < 400.. ok
should reject an error object when the returned statusCode is > 400.. ok
should reject an error object when requesting non-existent page.. ok
should reject an error object when there is an http error.. ok
request.SuperagentPromiseError
should have a originalError property if a child error is provided.. ok
should have a stack trace that includes the originalError stacktrace.. ok
cancelling promises
cancel without reason
should abort the request when the promise is cancelled.. fail
1: expected false to be true
should throw a bluebird CancellationError when the promise is cancelled without a reason.. fail
2: expected false to be true
cancel with reason that subclasses CancellationError
should abort the request when the promise is cancelled.. fail
3: expected false to be true
should throw a custom error when the promise is cancelled with a reason.. fail
4: expected false to be true
-> reporting 4 failures
1: superagent-promise cancelling promises cancel without reason should abort the request when the promise is cancelled
expected false to be true
<no lines in stack>
2: superagent-promise cancelling promises cancel without reason should throw a bluebird CancellationError when the promise is cancelled without a reason
expected false to be true
<no lines in stack>
3: superagent-promise cancelling promises cancel with reason that subclasses CancellationError should abort the request when the promise is cancelled
expected false to be true
<no lines in stack>
4: superagent-promise cancelling promises cancel with reason that subclasses CancellationError should throw a custom error when the promise is cancelled with a reason
expected false to be true
<no lines in stack>
-> failed 4 and passed 7 of 11 tests (112ms)
Unhandled rejection SuperagentPromiseError
I'm getting error when request response with 401, which blocks everything for about 10sec.
Any idea why?
The YUiCompressor does not like the catch function name and fails compressing the file and interprets it as a reserved keyword. Ideally that should be fixed in yuicompressor itself, but it does not seem to be trivial there, the issue is open for quite a while now.
So easy fix would be to just call the function like that: ['catch']()
Hi, thanks for the work! 👍
Was thinking if there is an easy way to return the res.body instead of res.
When attempting to import var request = require('superagent-bluebird-promise')
I get error: Uncaught TypeError: Promise.config is not a function
It took me a bit to realize how to catch SuperagentPromiseError with bluebird -- you have to reference the object that's within the required model. Slightly altered code for an examle:
var request= require('superagent-bluebird-promise');
request.get(URL)
.promise()
.catch(request.SuperagentPromiseError, function(err){
console.log(err.message);
console.log(err.body);
})
.catch(function(err){//show other errors
console.log(err);
});
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.