Promise What is the difference between return resolv () and resol ()?

read this example somewhere:

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 any difference

+23
javascript promise
source share
3 answers

return resolve() simply end the function as a normal return , which simply depends on the flow of your code. If you do not want or do not need any code to execute your function, use 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 promise state, but will execute code execution, if any, when return not used.

Remember to resolve() and reject() to create a promise state, they cannot be changed after creating the state, .then and .catch are used for further execution, the use of return depends entirely on your code stream. If you do not want to execute more code in this 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 is just like the normal return in function and has nothing to do with the promise

+31
source share

There is no difference here, but if you want to do something after the solution, see, for example, the examples at the bottom of the MDN page: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise / resolve

0
source share

I met a code error, and now I found out. allow and reject just change the state of the promise and affect the promise , but they do not change the state of the function in which they are .

Therefore, if you have code that should not run after permission or rejection, add a return statement.

-one
source share

All Articles