-3

How to convert the following method to an async method (syntax-wise):

const download = function(url, dest, callback){
    request.get(url)
    .on('error', function(err) {console.log(err)} )
    .pipe(fs.createWriteStream(`./voices/${dest}`))
    .on('close', callback);
};

This syntax isn't correct:

async function download(function(url, dest, callback)){
    request.get(url)
    .on('error', function(err) {console.log(err)} )
    .pipe(fs.createWriteStream(`./voices/${dest}`))
    .on('close', callback);
};

because function(url, dest, callabck) isn't recognized as a function.

fardin
  • 1,399
  • 4
  • 16
  • 27

1 Answers1

1

You use async when you want to await a function. In this case what you want is to return a Promise so that a method can call and await it's execution:

const download = (url, dest) => {
  return new Promise((resolve, reject) => {
    request.get(url)
      .on('error', reject)
      .pipe(fs.createWriteStream(`./voices/${dest}`))
      .on('close', resolve);
  });
};

Now you can use that function with await, usage:

async function somewhere() {
  try {
    await download('http://.../', 'dest');
    // code when completed
  }
  catch (err) {
    // code when error
  }
}

See more:

BrunoLM
  • 97,872
  • 84
  • 296
  • 452