0

Can someone explain me why this don´t work:

var outsideVar = 15;
myFunc.doSomething().then(function() {
  console.log("outsideVar: " + outsideVar);
}).fail(function(err) {
  console.log("error: ", err);
});

the output is error: undefined or outsideVar: undefined (depends if outsideVar is a variable or property of an object.

An outside variable should be accessible from inside the function or i´m wrong?

EDIT: I´m using this construction with spookyjs and it seems there is an issue with objects containing very long strings.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
solick
  • 2,325
  • 3
  • 17
  • 29
  • 2
    The code snippet looks ok. Can you provide more info? – mati Apr 29 '15 at 16:44
  • It works for me after replacing `myFunc.doSomething()` with `Promise.resolve()` and `.fail()` with `.catch()`. – greim Apr 29 '15 at 16:47
  • You want `.catch` and not `.fail`? – Benjamin Gruenbaum Apr 29 '15 at 16:52
  • Oh yes, there is no `fail` method in the Promise prototype. You should use `catch` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Promise_prototype – mati Apr 29 '15 at 16:53
  • What do you mean by "*depends if outsideVar is a variable or property*"? Also, if it logs `error: undefined` then this means that `doSomething` rejects the promise with a non-descriptive thing. – Bergi Apr 29 '15 at 16:59

1 Answers1

1

In NodeJS, you would use a function for the error. Like so:

myPromise.then(function() {
  // callback, executed on successful promise resolution
}, function() {
  // errback, executed on rejection
}, function() {
  // progressback, executed if the promise has progress to report
});

.fail() isn't a recognizable function in node, unless you have defined the .fail() function explicitly. The .fail() is throwing the undefined error. .fail() in nodejs is used for building unit tests, not promises. https://nodejs.org/api/assert.html

Otherwise, written properly, the closure should work. This is typical closure syntax. See Is promise a closure? for more details for promises with closures.

EDIT You could also use .catch() instead of an explicit error function.

Community
  • 1
  • 1
Olivercodes
  • 1,048
  • 5
  • 17