2

How can i return this function a promise
i want to return this function a promise function but don't know how to return a promise

 return new Promise((resolve, reject) => {});
async function readFile(filePath) {
  const myInterface = readline.createInterface({
    input: fs.createReadStream(filePath),
  });
  const arrayLink = [],
    arrayName = [];

  for await (const line of myInterface) {
    let temp = line.split(",");
    arrayLink.push(temp[0]);
    arrayName.push(temp[1]);
  }
  return [arrayLink, arrayName];
}
  • 1
    You can't make a function `promise` but can return `promise` from a function. – DecPK Apr 19 '21 at 05:25
  • How @decpk return a `promise` ? –  Apr 19 '21 at 05:27
  • Do you want to return `promise` from `readFile` function? – DecPK Apr 19 '21 at 05:28
  • yes @decpk from `readFile` –  Apr 19 '21 at 05:33
  • 1
    `readFile` already returns a promise, since it's [async function](https://stackoverflow.com/questions/51338277/async-function-returning-promise-instead-of-value). It's not clear what you need to do here. – VLAZ Apr 19 '21 at 05:37

1 Answers1

-1

You can return a promise from the function. But in that case, to make that function async does not make any sense though it will work fine.

When a function returns a promise you don't need to write then block. You can handle it with await keyword. Whatever you provided in resolve() function, you will get that value in variable - result

If you want to return a promise from your function following is the way.

function readFile() {
return new Promise((resolve, reject)=>{

    // your logic
    if(Success condition met) {
        resolve(object you want to return);
    }else{
        reject(error);
        // you can add error message in this error as well
    }
 });
}

async function fileOperation() {
  let result = await readFile();
}
pritampanhale
  • 106
  • 10