如何使用 javascript promises 执行相同的函数?

How can I make the same function execute with javascript promises?

我想使用 Javascript 承诺将同一个函数执行三次。每次调用该函数时,都会逐行读取文本文件,并将每行的答案写入另一个文本文件。我希望 javascript 承诺等到上一个函数完成,但由于某种原因,它只是一次 运行 三个函数,从而一次写入三个文件。由于我正在处理一个大文件,一次写入三个文本文件需要很长时间。

任何人都可以帮我弄清楚如何正确 运行 吗?我是 Promises 的新手,需要我能得到的所有帮助。

这是我的代码:

function verifyTransactions(fileName,functionName,obj,depth){
    var rd = readline.createInterface({
      input: fs.createReadStream('../paymo_input/stream_payment.csv'),
      output: process.stdout,
      terminal: false
    });
    rd.on('line', function(line) {
      var userData = extractUserData(line)
      if (userData !== undefined){
        var id1 = userData[0], id2 = userData[1];
        if (obj[id1]){
          console.log(id1)
          fs.appendFileSync('../paymo_output/'+fileName     +'.txt',functionName(obj,id1,id2,depth)+"\n", "UTF-8",{'flags': 'a'});
        }
        else{
          console.log("nope")
          fs.appendFileSync('../paymo_output/'+fileName+'.txt', "unverified"+"\n", "UTF-8",{'flags': 'a'});
        }
      }
    });
    rd.on('end',function(){
      console.log("ON TO THE NEXXTTTTT")
    })
}

Promise.resolve("output1")
  .then(function(file){
    verifyTransactions(file,pastTransaction,userTransactions);
    console.log("WRITING TO FILE TWO SOON")
    return "output2";})
  .then(function(file){
    verifyTransactions(file,breadthFirstSearch,userTransactions,2);
    return "output3";})
  .then(function(file){
    verifyTransactions(file,breadthFirstSearch,userTransactions,4);
    return "FINITO!!!";})
  .then(function(file){
    console.log(file);
  })

如果你想使用 Promises 等待函数完成它的工作,你需要做三件事:

  1. return 来自该函数的未解决的 Promise 对象
  2. 在该函数内,一旦您确定该函数已完成其工作,就解析 Promise
  3. 无论你在哪里调用那个函数,你都需要等待它的 Promise 解决,然后再做更多的事情。这是通过 .then().
  4. 完成的

换句话说:

function myFunction(input) {
   var promise = new Promise();

   /* do some things, then: */
   someEventEmitter.on('myEvent', function() {
     promise.resolve(returnValue); // all done!
   });

   return promise;
}

myFunction(input1)
  .then((function(result) { // run this function once the Promise has resolved
    console.log('myFunction returned: ' + result);
   });

如果您想使用 Promises 按顺序执行多个异步操作,您需要执行所谓的 promise 链:

myFunction(input1) // returns a Promise, which has a .then() method
  .then(function(result) {
    console.log('first result: ' + result);
    return myFunction(input2); // return a new Promise from inside of the function passed to .then()
  }) // this new Promise has a .then() method of its own
  .then(function(result2) {
    console.log('second result: ' + result2);
    return myFunction(input3);
  })
  .then(function(result3) {
    console.log('third result: ' + result3);
  });