Newboy11
Newboy11

Reputation: 3136

How to properly create a promise in javascript

I've created a promise function that returns error TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received undefined

 async function DlFile(url, fileName) {
  return new Promise ((fulfill, reject) => {
      https.get(url, function(res){
        const fileStream = fs.createWriteStream(`C:\\Users\\Garingo-PC\\Documents\\${fileName}.pdf`);
        res.pipe(fileStream);
    
        fileStream.on("error", reject);
    
        fileStream.on("finish", fulfill({
          status: 'ok'
        }));
      });
    }); 
  
}

const Main = async () => {
  const result = await DlFile(url, filename);
  console.log(result); //returns undefined
}

it should return some an object if it finished downloading the file

Upvotes: 0

Views: 45

Answers (1)

Toan Quoc Ho
Toan Quoc Ho

Reputation: 3378

fileStream.on("finish")'s param supposed to be a function, but you're not entering a function into it. fulfill is a callback but you've called it before you pass it into the finish callback. The correct way to use fulfill is that you have to call it when finish event is triggered. Like so:

fileStream.on("finish", () => {
    fulfill({ // Call when finish event being fired
      status: 'ok'
    })
});

Upvotes: 1

Related Questions