Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,26 @@ exports.fromCallback = function (fn) {
return Object.defineProperty(function (...args) {
if (typeof args[args.length - 1] === 'function') fn.apply(this, args)
else {
// Capture stack trace of where the promise was created in case it rejects.
let caller_stack = new Error("Failing function was called from here").stack
return new Promise((resolve, reject) => {
fn.call(
this,
...args,
(err, res) => (err != null) ? reject(err) : resolve(res)
(err, res) => {
if (err != null) {
if (err instanceof Error && typeof err.stack === 'string') {
// It is safe to improve the error's stack trace with
// information about where the Promise was created and where
// the err was passed from.
let e = new Error("Callback-based function called back with an error")
err.stack += "\n" + e.stack + "\n" + caller_stack
}
reject(err)
} else {
resolve(res)
}
}
)
})
}
Expand Down