Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise. What is the difference between return resolve() and resolve()?

somewhere read this example:

return new Promise( (resolve, reject) => {   fs.readFile(file, (err, data) => {     if (err) reject(err)     return resolve(data)   }) }) 

but I usually do this:

return new Promise( (resolve, reject) => {   fs.readFile(file, (err, data) => {     if (err) reject(err)     resolve(data)   }) }) 

is there a difference?

like image 499
ivanesi Avatar asked Feb 20 '17 16:02

ivanesi


People also ask

Is Promise resolve same as return?

resolve("aaa") is the same as return Promise. resolve(Promise. resolve("aaa")) - since resolve is idempotent calling it on a value more than once has the same result.

What does resolve () do in a promise?

resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

What does return a promise mean?

Wait until all promises have settled (each may fulfill or reject). Returns a Promise that fulfills after all of the given promises is either fulfilled or rejected, with an array of objects that each describe the outcome of each promise.

Is Promise resolve a promise?

Promise. resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened: If the value is a promise then promise is returned.


1 Answers

return resolve() will just end the function execution as a normal return, that just depends on the flow of your code, If you don't want or need any more code in your function to execute, then use a return to exit the function

return new Promise( (resolve, reject) => {   fs.readFile(file, (err, data) => {     if (err) reject(err)     return resolve(data)     console.log('after return') // won't execute   }) }) 

only resolve will create a successful state of promise, but will execute the code execution if there are any when return is not used.

Remember resolve() and reject() create the state of promise, they can't be changed once the state is created, .then and .catch handlers are used for further execution, using return entirely depends on your code flow. If you don't want to execute more code in that block, then return resolve()

return new Promise( (resolve, reject) => {   fs.readFile(file, (err, data) => {     if (err) reject(err)     resolve(data)     console.log('after return') // will execute   }) }) 

it's just same as a normal return statement in a function and has nothing to do with a promise

like image 108
Parwat Kunwar Avatar answered Sep 23 '22 23:09

Parwat Kunwar