質問

I have some code that opens and reads a SQL script file and opens a connection to the database in parallel, when they are done it executes the contents of the file on the connection. However, the connection result needs to be 'closed'. I need to be able to handle the case where the database connection succeeds and reading the file fails (wrong filename perhaps) and still close the connection in either case.

Here is the code I am currently using, it has a finally() handler to close the client if the query succeeds or fails, but if the file read fails the client will not be closed.

function execFile(db, file) {
    console.log('Connecting to ' + db);
    return Promise.all([
        connect('postgres://' + credentials + host + '/' + db),
        fs.readFileAsync(file, 'utf8')
    ]).spread(function(client, initSql) {
        console.log('Connected to ' + db);
        console.log('Running init script ' + file);
        return client.queryAsync(initSql).finally(client.end);
    });
}

I played a little with the bind() function to pass the client into the finally block but I'm not very happy with the complexity that it introduces. I have a feeling that settle() could be useful here and I'm playing with that now.

What is the best way to handle this?

役に立ちましたか?

解決

function execFile(db, file) {
    console.log('Connecting to ' + db);
    var client = connect('postgres://' + credentials + host + '/' + db);
    var initSql = fs.readFileAsync(file, 'utf8');
    return Promise.all([client, initSql]).spread(function(client, initSql) {
        console.log('Connected to ' + db);
        console.log('Running init script ' + file);
        return client.queryAsync(initSql);
    }).finally(function() {
       if (client.isFulfilled()) client.inspect().value().end();
    });
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top