如何使用javascript承诺执行相同的函数?
我想使用Javascript承诺执行相同的函数三次。每次调用函数时,逐行读取一个文本文件,并将每行的答案写入另一个文本文件。我希望javascript承诺等待前一个函数完成,但出于某种原因,它只是一次运行三个函数,从而一次写入三个文件。由于我正在处理一个大文件,一次写入三个文本文件需要很长时间 有人能帮我弄清楚如何正确运行吗?我对承诺不熟悉,需要所有能得到的帮助 这是我的密码:如何使用javascript承诺执行相同的函数?,javascript,promise,es6-promise,Javascript,Promise,Es6 Promise,我想使用Javascript承诺执行相同的函数三次。每次调用函数时,逐行读取一个文本文件,并将每行的答案写入另一个文本文件。我希望javascript承诺等待前一个函数完成,但出于某种原因,它只是一次运行三个函数,从而一次写入三个文件。由于我正在处理一个大文件,一次写入三个文本文件需要很长时间 有人能帮我弄清楚如何正确运行吗?我对承诺不熟悉,需要所有能得到的帮助 这是我的密码: function verifyTransactions(fileName,functionName,obj,depth
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);
})
如果要使用承诺等待函数完成其工作,则需要做三件事:
实现的。然后()
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);
});
如果您希望使用承诺按顺序执行多个异步操作,则需要执行所谓的承诺链接:
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);
});
我尝试了你的建议,但只运行了第一个函数。我是否需要承诺。解决(返回值)?返回值可以是“完成”吗?谢谢你的帮助!我做了你上面建议的改变。我还意识到我的主要问题是resolve()从未返回,因为rd.on('end')…不存在。它应该是rd.on('close',…)