Reputation: 36247
This is a basic question. I'm working through a js/node workshop on async programming called promise-it-wont-hurt. I have the following exercise:
// Let’s build a simple script to prove to ourselves that promises may only
// resolve one time and all future attempts to resolve them will simply be ignored.
// First, create a promise using the Promise constructor as we have been doing.
// In the promise’s executor, immediately attempt to fulfill the promise with a
// value of 'I FIRED'.
// Then, after the fulfill call, immediately try to reject the promise with an
// Error created with parameter 'I DID NOT FIRE'.
// After the promise creation, create a function onRejected with one parameter
// error that prints the Error’s message with console.log.
// Lastly, pass console.log and the function you just created as the success
// and rejection handlers respectively.
// If successful, your script should only log “I FIRED” and should not log
// “I DID NOT FIRE”.
my test.js contains:
var promise = new Promise(function(resolve, reject) {
() => {resolve("I FIRED")},
() => { reject(new Error("I DID NOT FIRE"))}
});
function onReject (error) {
console.log(error.message);
}
promise.then(x =>console.log(x),error =>onReject(error))
I'm a little unsure about:
// Lastly, pass console.log and the function you just created as the success
// and rejection handlers respectively.
I've rewritten this as:
promise.then(x =>console.log(x),error =>onReject(error))
However this produces no output at the command line. Experts can you please explain where my error is?
Upvotes: 0
Views: 129
Reputation: 156
You need to return the promise.
const madeOrder = bool => new Promise((res,rej) => {
if(bool) res('HE MADE AN ORDER!');
rej('HE DIDNT MAKE AN ORDER :(');
})
madeOrder(true)
.then(res => console.log(res))
.catch(err => console.log(err));
Upvotes: 1
Reputation: 56
Also new to JS Promises, but I believe this is because the resolve() and reject() are inside of their own functions that are not called.
I tried changing the promise to this:
var promise = new Promise(function(resolve, reject) {
resolve("I FIRED");
reject(new Error("I DID NOT FIRE"));
});
It seemed to have the desired efffect when I tested in the Chrome DevTools Console.
Upvotes: 3