Skip to content

Commit

Permalink
Fixed petkaantonov#1314: yielding a function should not call the func…
Browse files Browse the repository at this point in the history
…tion

   When rejecting a non-promise value, string.replace is used,
    and the value is passed as second parameter.
    But string.replace, if the second value is a function, will
    call that function.
    This commit fixes this by using value.toString().
  • Loading branch information
Gil Tayar committed Jan 4, 2017
1 parent d9a3a62 commit c7f55fb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 13 deletions.
3 changes: 2 additions & 1 deletion src/generators.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,8 @@ PromiseSpawn.prototype._continue = function (result) {
if (maybePromise === null) {
this._promiseRejected(
new TypeError(
YIELDED_NON_PROMISE_ERROR.replace("%s", value) +
YIELDED_NON_PROMISE_ERROR.replace("%s",
value == null ? value : value.toString()) +
FROM_COROUTINE_CREATED_AT +
this._stack.split("\n").slice(1, -7).join("\n")
)
Expand Down
40 changes: 28 additions & 12 deletions test/mocha/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,22 @@ describe("yielding", function() {
assert.equal(val, 4);
});
});

specify("yielding a function should not call the function", function() {
let functionWasCalled = false;
return Promise.coroutine(function*(){
try {
yield (function() {functionWasCalled = true;});
}
catch(e){
assert(e instanceof TypeError);
assert.equal(functionWasCalled, false);
return 4;
}
})().then(function(val){
assert.equal(val, 4);
});
});
});

describe("thenables", function(){
Expand Down Expand Up @@ -367,7 +383,7 @@ describe("Spawn", function() {
describe("custom yield handlers", function() {
specify("should work with timers", function() {
var n = 0;
return Promise.coroutine.addYieldHandler(function(v) {
Promise.coroutine.addYieldHandler(function(v) {
if (typeof v === "number") {
n = 1;
return Promise.resolve(n);
Expand Down Expand Up @@ -417,18 +433,18 @@ describe("custom yield handlers", function() {
});
});

Promise.coroutine.addYieldHandler(function(v) {
if (typeof v === "function") {
var cb;
var promise = Promise.fromNode(function(callback) {
cb = callback;
});
try { v(cb); } catch (e) { cb(e); }
return promise;
}
});

specify("should work with thunks", function(){
Promise.coroutine.addYieldHandler(function(v) {
if (typeof v === "function") {
var cb;
var promise = Promise.fromNode(function(callback) {
cb = callback;
});
try { v(cb); } catch (e) { cb(e); }
return promise;
}
});

var thunk = function(a) {
return function(callback) {
setTimeout(function(){
Expand Down

0 comments on commit c7f55fb

Please sign in to comment.