Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript How to Make a Promise?

Zack Guo
Zack Guo
12,135 Points

Why the console.log can be replaced by resolve?

var calculationPromise = new Promise (
    function(resolve, reject){
        setTimeout(funtion(){
            resolve(1+1); //what's the resolve func anyway? 
        })
    }
)

calculatePromise.then(function(value){
    console.log("The value is ", value);
})

1/what's the resolve function at line 4 anyway? 2/What's the value in then function? the "value" means "resolve(1+1);"? or "(1+1)" or setTimeout? why?

Thanks

The result that the promise function returns (from resolve) is passed as the argument of the next function (value).

2 Answers

Consider

const aPromise = new Promise(function executor(resolve, reject) {})
  1. resolve and reject functions are provided by the Promise constructor to your executor (the function provided to the Promise call).
    • calling resolve(value) sets the promise's (aPromise) fulfillment value to value.
    • calling reject(error) or throwing an error in executor sets the promise's rejection value to the error.
  2. The then method's first argument is a fulfillment handler, which takes the promise's fulfillment value as its argument: in aPromise.then(onFulfillment), if the executor calls resolve(value), then onFulfillment(value) is called with that same value. As the videos explain, this happens, because it's what promises do. In your example, that value is 2.
hector alvarado
hector alvarado
15,796 Points

Console run math operations, so it displays a 2 in the console. The objective I think its code re usability, If he name it a function he can call it several times to run it asynchronous. (in the example it just an anonymous function to add 1 +1 )