Skip to content

Commit 57ae713

Browse files
Merge pull request then#46 from TooTallNate/fix/nodeify-this-context
pass through the `this` context in nodeify()
2 parents 5a0cfbc + 5bd912c commit 57ae713

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

index.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,15 @@ Promise.nodeify = function (fn) {
8686
return function () {
8787
var args = Array.prototype.slice.call(arguments)
8888
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
89+
var ctx = this
8990
try {
90-
return fn.apply(this, arguments).nodeify(callback)
91+
return fn.apply(this, arguments).nodeify(callback, ctx)
9192
} catch (ex) {
9293
if (callback === null || typeof callback == 'undefined') {
9394
return new Promise(function (resolve, reject) { reject(ex) })
9495
} else {
9596
asap(function () {
96-
callback(ex)
97+
callback.call(ctx, ex)
9798
})
9899
}
99100
}
@@ -161,16 +162,16 @@ Promise.prototype.done = function (onFulfilled, onRejected) {
161162
})
162163
}
163164

164-
Promise.prototype.nodeify = function (callback) {
165+
Promise.prototype.nodeify = function (callback, ctx) {
165166
if (typeof callback != 'function') return this
166167

167168
this.then(function (value) {
168169
asap(function () {
169-
callback(null, value)
170+
callback.call(ctx, null, value)
170171
})
171172
}, function (err) {
172173
asap(function () {
173-
callback(err)
174+
callback.call(ctx, err)
174175
})
175176
})
176177
}

test/extensions-tests.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,20 @@ describe('extensions', function () {
101101
done()
102102
})
103103
})
104+
it('passes through the `this` argument', function (done) {
105+
var ctx = {}
106+
var add = Promise.nodeify(function (a, b) {
107+
return Promise.resolve(a)
108+
.then(function (a) {
109+
return a + b
110+
})
111+
})
112+
add.call(ctx, 1, 2, function (err, res) {
113+
assert(res === 3)
114+
assert(this === ctx)
115+
done()
116+
})
117+
})
104118
})
105119
describe('Promise.all(...)', function () {
106120
describe('an array', function () {
@@ -220,5 +234,20 @@ describe('extensions', function () {
220234
done()
221235
})
222236
})
237+
it('accepts a `context` argument', function (done) {
238+
var ctx = {}
239+
function add(a, b, callback) {
240+
return Promise.resolve(a)
241+
.then(function (a) {
242+
return a + b
243+
})
244+
.nodeify(callback, ctx)
245+
}
246+
add(1, 2, function (err, res) {
247+
assert(res === 3)
248+
assert(this === ctx)
249+
done()
250+
})
251+
})
223252
})
224253
})

0 commit comments

Comments
 (0)