简体   繁体   中英

How to return a promise function using node js

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];
}

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

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