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

Javascriptnode.jsPromise

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionivanesiView Question on Stackoverflow
Solution 1 - JavascriptParwat KunwarView Answer on Stackoverflow