Why does the 'new promise (...)' return 'undefined'?

It seems that if the "allow" function does not refer to the function that is used to create the promise, then the promise is undefined. In the code below, ...

var count = 0; var limit = 3; // var thePromise; function timeout(_count) { thePromise.resolve(_count); } function sendMessage() { return new Promise(function(resolve, reject) { if (++count > limit) { reject({'Limit Exceeded': count}); } else { // With this line in place, the return value from this function // (expected to be a promise) is undefined setTimeout(timeout.bind(null, count), 1000); // If the line above is replaced by this, it works as expected // setTimeout(/*timeout.bind(null, count)*/function (_count) { // resolve(_count); // }.bind(null, count), 1000); } }); } function sendAnother(_count) { console.log('Resolved with count %j', _count); return sendMessage(); } function detectError(_error) { console.log('Rejected with %s', JSON.stringify(_error)); process.exit(1); } thePromise = sendMessage(); thePromise = thePromise.then(function (_count) { return sendAnother(_count)}, function(_error) {detectError(_error)}); 

trying to execute a decision outside the function that creates the promise results in:

 node-promises.js:6 thePromise.resolve(_count); ^ TypeError: undefined is not a function at timeout (node-promises.js:6:16) at Timer.listOnTimeout (timers.js:110:15) 

But if line 16 is commented out, and lines 18-20 without commenting, the output is:

 Resolved with count 1 

..that is what I expected. What am I missing? This uses nodejs v0.12.2 for Windows 7, if that matters.

+6
source share
1 answer

This is due to this line:

 thePromise.resolve(_count); 

there is no resolve function on this object. resolve comes from the function you created when creating the new promise:

 return new Promise(function(resolve, reject) { 

Commenting on this line and using an alternative function, you call the correct resolve() , which causes the desired output. One option to fix this might be to pass the permission function to your timeout, for example:

 function timeout(resolve, _count) { resolve(_count); } 

Although I'm not sure why you would like to do this.


Your heading asks why new Promise returns undefined when the point is that it is not. It really returns a real promise. Just resolve not a valid function for a promise object.

+7
source

All Articles