George Edwards
George Edwards

Reputation: 9229

Retry Promise on error - Typescript

I have a nodeJS application using the mssql driver to interact with my SQL database. I want to have a single function to get a value from a database, however, on first use, the table won't exist, so if there is a specific error, I want to call my createValue() function. The code below works, but I have to call it twice to get the value. Basically, if the condition in the .catch is met, I would like to call the Request again. Is there a neat way of doing this?

var value;
new sql.Request().query('select * from _table')
    .then(function (recordset) {
        value = recordset;
    })
    .catch(function (err) {
        console.log("Query Error: " + err);
        if (err.message == "Invalid object name '_table") {
            createValue();
        }
    })

Update:

I now have the following function, but how should I best get it to return recordset?

function getData() {
    sql.connect("mssql://username:password@localhost/mytestdatabase").then(function () {
        return new sql.Request().query('select * from _table')
            .then(function (recordset) {
                console.log(recordset); // <-- THIS IS WHAT I WANT TO RETURN
            })
            .catch(function (err) {
                console.log("Query Error: " + err);
                if (err.message == "Invalid object name '_table") {
                    updateValue();
                    return getData();
                }
                return null;
            })
    }).catch(function (err) {
        console.log("Connection Error: " + err);
    })
};

Upvotes: 0

Views: 1272

Answers (1)

memimomu
memimomu

Reputation: 161

You can wrap it in a function, which you can then call recursively. I'm assuming createValue() is synchronous.

function getData(){
    return new sql.Request().query('select * from _table')
    .catch(function (err) {
        if (err.message == "Invalid object name '_table") {
            createValue();
            return getData();
        }
        throw err;
    });
}

...

var resultsetPromise = getData();
resultsetPromise.then( function(resultset){
    // do something with your data
}).catch( function(err){
    console.log("Query Error: " + err);
});

Upvotes: 1

Related Questions