diff --git a/lib/client.js b/lib/client.js index 62b2d38..1c19623 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1,3 +1,5 @@ +'use strict'; + const EventEmitter = require('events'); const crypto = require('crypto'); @@ -263,7 +265,7 @@ class Client extends EventEmitter { */ get(url, data, callback) { if (!url) { - throw new Error('url is required'); + return Promise.reject(new Error('url is required')); } if (typeof data === 'function') { @@ -277,10 +279,8 @@ class Client extends EventEmitter { } if (!this.authed) { - return new Promise((resolve) => { - // If not connected, do auth to get updated versions first - this.getPendingAuth(url, data, callback, resolve); - }); + // If not connected, do auth to get updated versions first + return this.getPendingAuth(url, data, callback); } // Indicates whether to check the request cache or not @@ -301,23 +301,35 @@ class Client extends EventEmitter { return this.request('get', url, data, callback); } - getPendingAuth(url, data, callback, resolve) { - if (this.requestsPendingAuth) { - this.requestsPendingAuth.push({ url, data, callback, resolve }); - return; - } + getPendingAuth(url, data, callback) { + return new Promise((resolve, reject) => { + if (this.requestsPendingAuth) { + this.requestsPendingAuth.push({ url, data, callback, resolve }); + return; + } - this.requestsPendingAuth = []; + this.requestsPendingAuth = []; - this.authWithKey(() => { - this.get(url, data, (_err, result, headers) => { - if (callback) { - callback(null, result, headers); - } - resolve(result); - }); + this.authWithKey(() => { + this.get(url, data, (err, result, headers) => { + if (typeof callback === 'function') { + callback(err, result, headers); + } + if (err) { + reject(err); + return; + } + + resolve(result); + }) + .catch((err) => { + reject(err.message); + }); + }); + }).then((result) => { this.flushRequestsPendingAuth(); + return result; }); } diff --git a/lib/connection.js b/lib/connection.js index 9b4ad3a..9fc52b9 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -1,3 +1,5 @@ +'use strict'; + const EventEmitter = require('events'); const tls = require('tls'); const net = require('net');