Object is possibly undefined in TypeScript - javascript

I did use sfDoc !== undefined, but still I'm getting the error of object is possibly undefined. Am I doing anything wrong here?
return database.runTransaction(function (transaction) {
return transaction.get(sfDocRef).then(sfDoc => {
if (!sfDoc.exists) {
throw "Document does not exist!";
}
if (sfDoc !== undefined) {
var usedCount = sfDoc.data().usedCount + 1;
transaction.update(sfDocRef, { usedCount: usedCount });
}
return transaction;
});
}).then(function () {
console.log("Tag field changed!");
return true;
}).catch(function (error) {
console.log("Error in changing Tag field: ", error);
return false;
});

Try this example. Check for the sfDoc and return transaction.update, So that then wait to resolve the promise. According to document, you don not has to check for sfDoc. It will be always defined.
return database
.runTransaction(function (transaction) {
return transaction.get(sfDocRef).then((sfDoc) => {
if (sfDoc && sfDoc.exists) {
var usedCount = sfDoc.data().usedCount + 1;
return transaction.update(sfDocRef, { usedCount: usedCount });
} else {
throw "Document does not exist!";
}
});
})
.then(function () {
console.log("Tag field changed!");
return true;
})
.catch(function (error) {
console.log("Error in changing Tag field: ", error);
return false;
});

Related

RXJS error handling and wrapping multiple calls

Is there a better way to orchestrate the below code in Rxjs ?
and from Javascript perspective Promise/Asyc/Await which will be better considering some hard error and soft error handlings.
Couple of calls are hard dependency which are marked as hard true in the error and on subsequent error handler checks and re throw it. and soft errors are added to final data.error for any processing based on the soft errors.
How this can be better done ?
const { Observable } = require('rxjs');
const { map, filter, flatMap, concatMap } = require('rxjs/operators');
function testcallback(fail, callback) {
if (fail == true) {
setTimeout(function(){ callback(new Error({ message: "Operation failed" })); }, 100);
}
else {
setTimeout(function(){ callback(null, 10); }, 100);
}
}
function createData(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function associateData(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function removeData(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function markAssociateSuccess(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function removeOldData(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function getAllData() {
return Observable.of( {error:null, data:[333]});
}
function updateData(updateData) {
let param = updateRequest.param;
return createData(1 == param)
.catch((err) => {
err.errorStep = 'CREATE_DATA';
err.hard = true;
throw (err);
}).flatMap(
() => {
return associateData(2 == param)
.catch((err) => {
err.errorStep = 'ASSOCIATE_DATA';
err.hard = true;
return removeData(3==param)
.map(() => {
throw (err);
});
});
},
(createDataResponse, associateDataResponse) => {
return [createDataResponse, associateDataResponse];
}
)
.flatMap(() => {
if (updateData.markAssociationSuccess) {
return markAssociateSuccess(4 == param);
} else {
return Observable.of({});
}
}).catch((err) => {
if (err.hard) {
throw (err);
}
err.errorStep = 'ASSOCIATE_SUCCESS';
return Observable.of({ error: err });
})
.flatMap((data) => {
if (data.error) {
return Observable.of(data);
}
return removeOldData(5 == param);
}).catch((err) => {
if (err.hard) {
throw (err);
}
err.errorStep = 'REMOVE_OLD_DATA';
return Observable.of({ error: err });
})
.flatMap(
function fetchData() {
return getAllData();
},
function resultSelector(prevRes, { error, data }) {
if (error) {
return {};
}
if (prevRes.error) {
data.error = prevRes.error;
}
return data;
}
)
.subscribe(
function onNext(data) {
console.log("Successful operation final data: " + data);
},
function onError(err) {
console.log("Errored out" + JSON.stringify(err));
},
function onComplete() {
console.log("Stream got completed");
}
);
}
const updateRequest = {
param:1,
markAssociationSuccess: true
}
updateData(updateRequest);

(...).then is not a function

I need to fix the error on code below, can someone help me please?. The code is written on JS(NodeJs). The error is this (...).then is not a function. Thanks.
try {
var decoded = jwt.decode(JWTToken, { complete: true });
var audience = decoded.payload.aud;
return db.checkAudience(audience).then(ehClient => {
if (ehClient == true) {
return db.getCreditsGeneral(sgecode, collections, year).then(total => {
let result = [];
total.forEach(item => {
result.push({
collection: item.Sistema,
levelType: item.idNivelEnsino,
grade: item.codPortal
});
});
return result;
});
} else {
return "not authorized";
}
});
} catch (err) {
return { erro: err.message };
}

Promise resolution

I am new to javascript promises, I am using below code from NativeScript to query sqlite database and just want to return true if row exists and false otherwise:
function hasBookmark(url) {
(new Sqlite("pakjobs.db")).then(db => {
db.all("SELECT url FROM bookmarks WHERE url=?", [url]).then(rows => {
return rows.length ? true : false;
}, error => {
console.log("hasBookmark ERROR", error);
return false;
});
}, error => {
console.log("hasBookmark ERROR", error);
return false;
});
return false;
}
However function ALWAYS returns false.
Can anybody tell how do I return true if row exists and false otherwise ?
Thanks for the help
You are not going to be able to return true or false, that's pretty much the point of Promises, you can't return something asynchronously in javascript.
What you can do, however, is directly returning the Promise you're creating and then calling .then on it.
function hasBookmark(url) {
return (new Sqlite("pakjobs.db")).then(db => {
return db.all("SELECT url FROM bookmarks WHERE url=?", [url]).then(rows => {
return rows.length ? true : false;
}, error => {
console.log("hasBookmark ERROR", error);
return false;
});
}, error => {
console.log("hasBookmark ERROR", error);
return false;
});
}
const hasBookmarkPromise = hasBookmark('someurl');
hasBookmarPromise.then(value => {
if (value === true) {
console.log('has bookmarks');
}
});
function hasBookmark(url) {
return new Promise((resolve, reject) => {
(new Sqlite("pakjobs.db")).then(db => {
db.all("SELECT url FROM bookmarks WHERE url=?", [url]).then(rows => {
resolve(rows.length ? true : false)
}, error => {
console.log("hasBookmark ERROR", error);
resolve(false);
});
}, error => {
console.log("hasBookmark ERROR", error);
resolve(false);
});
});
}
hasBookmark(url).then(function(isValid){
If(isValid){
// Do something
}
});

Sails: How to return a value from the find function

I am working in sails js. And i want to return the variable sequence[0].NextValue;. But I am not getting it.
function AutoGenerate(tablename)
{
Sequence.find({TableName:tablename}).exec(function(err,sequence){
if(err)
{
console.log("err");
return res.negotiate(err);
}
else
{
console.log(sequence);
var intCurrentNo = sequence[0].NextValue;
var intNextNo = sequence[0].NextValue + sequence[0].IncrementBy;
if (intNextNo < sequence[0].MinimumValue || intNextNo > sequence[0].MaximumValue)
{
console.log("Error While Updating UserId")
return res.badRequest('Next value not between the Minimum and Maximum value');
}
else
{
sequence[0].NextValue = intNextNo;
console.log(intNextNo);
sequence[0].save(function(err)
{
if (err)
{
console.log("error while update");
return res.negotiate(err);
}
else
{
console.log("Incremented");
console.log(sequence[0].NextValue);
return sequence[0].NextValue;
}
});
}
}
});
}
But the Sequence.find({TableName:tablename}) function does not returning any value. Please help me to get rid of this.
You can't return a value cause it's an asynchronous method you have to do it with callbacks :
function AutoGenerate(tablename, callback)
{
Sequence.find({TableName : tablename}).exec(function (err, sequence)
{
if (err)
{
console.log("err");
callback(err);
}
else
{
console.log(sequence);
var intCurrentNo = sequence[0].NextValue;
var intNextNo = sequence[0].NextValue + sequence[0].IncrementBy;
if (intNextNo < sequence[0].MinimumValue || intNextNo > sequence[0].MaximumValue)
{
console.log("Error While Updating UserId")
callback(new Error('Next value not between the Minimum and Maximum value'));
}
else
{
sequence[0].NextValue = intNextNo;
console.log(intNextNo);
sequence[0].save(function (err)
{
if (err)
{
console.log("error while update");
callback(err);
}
else
{
console.log("Incremented");
console.log(sequence[0].NextValue);
callback(null, sequence[0].NextValue);
}
});
}
}
});
}
And call it like this :
AutoGenerate("myTableName", function(err, nextValue){
if(err){res.negotiate(err);}
else {/* DO WHAT YOU WANT */}
});

Promises in angularjs controller - how to implement

I am trying to implement a basic function using promises in one of my controllers just so I can ensure it is working correctly before adding in more complex functionality. I am getting a "TypeError: undefined is not a function" on the ".then(function(data){" in the lockPromise method.
Function called from view
$scope.lockPromise = function(fieldId) {
$scope.getLockMessage2(fieldId).getWeather()
.then(function(data) {
if (data === "returned SUCCESS info") {
alert("data is good");
} else {
alert("FAILED");
}
}, function(error) {
alert(error);
});
};
Second function in ctrl
$scope.getLockMessage2 = function(fieldId) {
return{
getWeather: function() {
return $http.get('/api/getData')
.then(function(response) {
if (typeof response.data === "string") {
return response.data;
} else {
return $q.reject(response.data);
}
}, function(response) {
return $q.reject(response.data);
});
}
};
};
API GET
[Route("api/getData")]
public HttpResponseMessage GetData()
{
string data = JsonConvert.SerializeObject("returned SUCCESS info");
return new HttpResponseMessage
{
Content = new StringContent(data, Encoding.UTF8, "application/json")
};
}
EDIT 1:
code updated to reflect comments
Change
$scope.getLockMessage2(fieldId).then
to
$scope.getLockMessage2(fieldId).getWeather().then
Your $scope.getLockMessage2 return an object, not function.
I think the code should be (not tested):
$scope.lockPromise = function(fieldId) {
$scope.getLockMessage2(fieldId).getWeather()
.then(function(data) {
if (data === "good") {
alert("data is good");
} else {
alert("FAILED");
}
}, function(error) {
alert(error);
});
};

Categories