2

my question is that im running node.js, and i have 2 functions that needs to be run in a specific order, however they are not returning a promise at this this. So i wonder how would i rewrite this to make sure that the main function would return a promise, and if i have nested functions, do i just run the 2nd function from the 1st functions resolve?

Here is the code:

handleMd5Convert = (file) => {
  fs.readFile(file, (err, buf) => {
    fs.rename(file, directoryPath + md5(buf) + '.mp3', (err) => {
      if (err) console.log('ERROR: ' + err);
    })
  })
})

HandleMd5Convert should be able to to .then()

/Alex

2 Answers 2

5

You should be able to wrap the whole thing in a new Promise() and use resolve() & reject() to handle success and errors:

handleMd5Convert = (file) => {
  return new Promise((resolve, reject) => {
    fs.readFile(file, (err, buf) => {
      if (err) return reject(err)
      fs.rename(file, directoryPath + md5(buf) + '.mp3', (err) => {
        if (err) return reject(err);
        resolve()
      })
    })
  })
}

handleMd5Convert('test.txt')
.then(() => console.log("done"))
.catch(err => console.log("error:", err))
Sign up to request clarification or add additional context in comments.

6 Comments

The resolve() here, it shouldnt have anything inside of it? or just emtpy () is fine? if i were to console log this now, it would return undefined, but maybe it shouldnt return anything
@AlexanderMunckAfRosenschöld it's not required, but if you have a value you want to retrieve in the then() you can resolve that value. You would: resolve(someValue) then after the promise resolves you could get it in then(someValue => {/* use some value */}). It doesn't seem like you have anything to resolve in this case though, but maybe something like the final file name would make sense.
Thanks alot for your help!
@AlexanderMunckAfRosenschöld You should mark the answer as "accepted", if it worked for you. Do this by clicking the tick mark below vote buttons of this answer.
Why did you write return reject(err) instead of reject(err)? (inside the callback for fs.readFile function)
|
1

You can create a promise using new Promise like this:

var myPromise = function(resolve) {
    someAsyncMethod(param1, callback(x){
        resolve (x);
    });
}

This way myPromise is able to .then(). the promise will be completed only after you call resolve()

myPromise.then(function(result){
    // Your code here...
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.