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?
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