简体   繁体   English

如何使用节点 js 返回 promise function

[英]How to return a promise function using node js

How can i return this function a promise我怎样才能退回这个 function 和 promise
i want to return this function a promise function but don't know how to return a promise我想退回这个 function 和 promise function 但不知道如何退回 ZB321DE375DC299EC807D

 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.您可以从 function 返回 promise。 But in that case, to make that function async does not make any sense though it will work fine.但在这种情况下,使 function 异步没有任何意义,尽管它可以正常工作。

When a function returns a promise you don't need to write then block.当 function 返回 promise 时,您不需要写入然后阻塞。 You can handle it with await keyword.您可以使用 await 关键字来处理它。 Whatever you provided in resolve() function, you will get that value in variable - result无论您在 resolve() function 中提供什么,您都将在变量中获得该值 - 结果

If you want to return a promise from your function following is the way.如果您想从 function 返回 promise,方法如下。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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