简体   繁体   中英

Javascript promise, nested functions

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

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

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...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM