簡體   English   中英

如何使用節點 js 返回 promise function

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

我怎樣才能退回這個 function 和 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];
}

您可以從 function 返回 promise。 但在這種情況下,使 function 異步沒有任何意義,盡管它可以正常工作。

當 function 返回 promise 時,您不需要寫入然后阻塞。 您可以使用 await 關鍵字來處理它。 無論您在 resolve() function 中提供什么,您都將在變量中獲得該值 - 結果

如果您想從 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