nodejs:同步代码片段

时间:2017-09-25 11:14:06

标签: javascript node.js asynchronous

我正在使用fs.unlink删除一些文件,然后我想运行一些代码。由于JS的异步特性,正在发生的是取消链接后我的代码在unlink的回调之前被调用。我如何同步这个?承诺是唯一的方式吗?

fs.unlink("FileName",function(err){
   console.log("RUN");
})

for(let i = 0; i<10;i++) {
   console.log(i);
}

结果:

1
2
3
4
5
6
7
8
9
RUN

使用promises的问题在于:如果我要删除许多文件,那么我将保留承诺的数量,然后检查已解决的数量。这我想避免

4 个答案:

答案 0 :(得分:3)

在这种情况下,您可以使用fs.unlink try { fs.unlinkSync("FileName"); console.log('Removing file successful!'); } catch(e) { // TODO: handle errors here }; console.log("RUN"); for(let i = 0; i<10;i++) { console.log(i); } 的同步版本:

fs.unlink()

正如@Keith在评论中正确提到的:这样的同步操作应该谨慎使用。如果要删除大量文件,最好使用异步Sub RemoveWords() Dim i As Long Dim cellValue As String Dim stringLenth As Long Dim myString As String Dim words() As Variant words = Array("Many", "specific ", "Huawei", "tend", "Motorolla", "Apple") myString = "Biggest problem with many phone reviews from non-tech specific publications is that its reviewers tend to judge the phones in a vacuum" For i = 1 To 13 cellValue = Cells(i, 4).Value If Not IsEmpty(cellValue) Then stringLength = Len(cellValue) ' test if string is less than 100 If stringLength > 100 Then Call replaceWords(cellValue, stringLength, words) Else ' MsgBox "less than 100 " End If End If Next i End Sub Public Sub replaceWords(cellValue, stringLength, words) Dim wordToRemove As Variant Dim i As Long Dim endString As String Dim cellPosition As Variant i = 0 If stringLength > 100 Then For Each wordToRemove In words If InStr(1, UCase(cellValue), UCase(wordToRemove )) = 1 Then MsgBox "worked word found" & " -- " & cellValue & " -- " & key Else Debug.Print "Nothing worked" & " -- " & cellValue & " -- " & key End If Next wordToRemove Else MsgBox "less than 100 " End If End Sub ,因为你可以同时“启动”更多这些文件(权衡:启动太多,性能可能因I / O饱和而受损) )。

答案 1 :(得分:2)

使用Promises是一个很好的解决方案,您不必自己跟踪承诺,bluebird会为您完成:

const Promise = require('bluebird');

function unlinkFile(fileName) {
    return new Promise((resolve, reject) => {
        fs.unlink(fileName, function (err) {
            if (err) {
                return reject(err);
            }
            resolve();
        });
    });
}

Promise.all([unlinkFile('01.txt'), unlinkFile('02.txt'), unlinkFile('03.txt')])
    .then(() => {
        console.log('ALL FILES UNLINKED');
    });

// OR YOU CAN USE promise.map

const filesToUnlink = ['01.txt', '02.txt', '3.txt'];
Promise.map(filesToUnlink, unlinkFile)
    .then(() => {
        console.log('ALL FILES UNLINKED');
    });

答案 2 :(得分:0)

承诺不是唯一的方法。您可以将for循环包装在函数中,并从unlink回调中调用该函数。

fs.unlink("FileName",function(err){
    console.log("RUN");
    loop();
})

function loop() {
    for(let i = 0; i<10;i++) {
       console.log(i);
    }
}

另一方面,有了Promise,你会这样做:

new Promise((resolve, reject) => {
    fs.unlink("FileName",function(err){
        console.log("RUN");
        return resolve(); 
    });
})
.then(() => {
    for(let i = 0; i<10;i++) {
        console.log(i);
    }
});

但是,正如@robertklep所说,如果您的代码不需要异步,只需调用同步函数。

答案 3 :(得分:0)

你应该使用Promise来获得正确的结果。

let fs = require('fs');
new Promise((resolve,reject) => {
    fs.unlink("demo1.txt", function (err) {
        console.log("RUN");
        if(err)
            reject(err);
        resolve();
    })
})
.then(() => {
        for (let i = 0; i < 10; i++) {
            console.log(i);
        }
    },(error)=>{
        console.log(error);
    })
相关问题