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 trialZack Guo
12,135 PointsWhy 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
2 Answers
Luis Marsano
21,425 PointsConsider
const aPromise = new Promise(function executor(resolve, reject) {…})
-
resolve
andreject
functions are provided by thePromise
constructor to your executor (the function provided to thePromise
call).- calling
resolve(value)
sets the promise's (aPromise
) fulfillment value tovalue
. - calling
reject(error)
or throwing an error inexecutor
sets the promise's rejection value to the error.
- calling
- The
then
method's first argument is a fulfillment handler, which takes the promise's fulfillment value as its argument: inaPromise.then(onFulfillment)
, if the executor callsresolve(value)
, thenonFulfillment(value)
is called with that samevalue
. As the videos explain, this happens, because it's what promises do. In your example, thatvalue
is 2.
hector alvarado
15,796 PointsConsole 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 )
Marius Posogan
11,184 PointsMarius Posogan
11,184 PointsThe result that the promise function returns (from resolve) is passed as the argument of the next function (value).