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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With