Skip to content
Advertisement

Promise not fulfilled

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:

Create a promise. Have it fulfilled with a value of 'FULFILLED!' in
executor after a delay of 300ms, using setTimeout.

Then, print the contents of the promise after it has been fulfilled by passing
console.log to then.

my test.js file contains:

var promise = new Promise(function (fulfill, reject) {

  setTimeout(() => 'FULFILLED!',300);
});

promise.then((r)=> console.log(r));

When I run “node test.js” at the command line , I get no output. What am I doing wrong?

Advertisement

Answer

All this does is return the string 'FULFILLED!':

() => 'FULFILLED!'

But it doesn’t return it to anywhere. setTimeout certainly doesn’t do anything with that result, and neither does the Promise. To fulfill the Promise with a value, you have the fulfill function provided by the Promise itself:

() => fulfill('FULFILLED!')

(This is more commonly called resolve, but it doesn’t really matter what you call it as long as it’s the first parameter in the function passed to the Promise constructor.)

As you can imagine, to reject the Promise you’d call the reject function similarly.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement