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
}
});
Related
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);
I tried without success, to execute my Promise with Sequelize on stored procedure(MSSQL) inside the function, below the code (when I don´t use the Promise, this code runs perfectly, retrieving the json´s data):
function getData(numTravessia) {
return new Promise((resolve, reject) => {
return connection.query(
'EXEC [dbo].[SP_RECUPERAINFOTRAVESSIA] #ID=:param1',
{
replacements: {
param1: numTravessia,
},
type: QueryTypes.SELECT
},
(error, meta, body) => {
if (body != undefined) {
resolve(body.toString());
} else {
reject(error);
}
})
});
}
async function getInfoTravessia(numTravessia) {
try {
var r = await getData(numTravessia);
return JSON.parse(r);;
} catch (error) {
console.log(error);
}
}
app.listen(8000, () => {
console.log("aplicativo em execução");
getInfoTravessia(1955).then((result) => {
console.log(result);
}).catch((e) => {
console.log(e);
})
});
Below, follow the code snippet that I don´t use the Promise and it´s working:
connection.query(
'EXEC [dbo].[SP_RECUPERAINFOTRAVESSIA] #ID=:param1',
{
replacements: {
param1: 1955,
},
type: QueryTypes.SELECT
}).then((result) => {
// RETORNA UM STRING
var obj = result[0];
res.send(obj);
// return obj;
}).catch((e) => {
console.log('error', e);
});
Please, anyone can help me?
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;
});
I am doing with Ionic News App. I have one problem with getting a response from the service file.
home.page.ts
getNews(): void {
this.loading = true;
this.language = localStorage.language;
this.checkForToken();
var userId = this.loggedInUser;
this._newsService.getAllNews().subscribe(
(res: any) => {
console.log("all news==========>", res)
this.loadNewsToPage(res, userId);
},
(err) => {
this.loading = false;
this.error = err;
});
}
news.service.ts
getAllNews(){
if(this.network.type == 'none' ){
console.log(JSON.parse(localStorage.getItem("newsArray")));
this.newsArray = JSON.parse(localStorage.getItem("newsArray"))
return this.newsArray;
}else{
return this.http.get(config.baseApiUrl + 'news?isApproved=APPROVED').pipe(
map((res) => {
this.newsArray = res['data'];
localStorage.setItem('newsArray',JSON.stringify(this.newsArray))
return this.newsArray;
}),
catchError(this.handleError));
}
}
Now the problem is when the network is 'none' it goes in 'if' condition in service file and return response from local storage. But it gives me below error when network is none.
ERROR TypeError: this._newsService.getAllNews(...).subscribe is not a
function
It works properly when it goes in else condition or when a network is present. Why like this?
Your getAllNews function isn't an Observable. So you can't subscribe to it. See the example below where you return an Observable for the first if condition and the second else condition. You need to close the Observable with observer.complete() after each next function.
getAllNews(): Observable<any>{
return new Observable(observer => {
if(this.network.type == 'none' ){
console.log(JSON.parse(localStorage.getItem("newsArray")));
this.newsArray = JSON.parse(localStorage.getItem("newsArray"))
observer.next(this.newsArray);
observer.complete();
} else{
this.http.get(config.baseApiUrl + 'news?isApproved=APPROVED').subscribe(
(result: object) => {
this.newsArray = result['data'];
localStorage.setItem('newsArray',JSON.stringify(this.newsArray))
observer.next(this.newsArray);
observer.complete();
},
(error) => {
observer.error(error);
});
}
});
}
You can now access the next block in your subscribe > result and the error block in subscribing> error.
this._newsService.getAllNews().subscribe(
(res: any) => { // observer.next() brings you here
console.log("all news==========>", res)
this.loadNewsToPage(res, userId);
},
(err) => { // observer.error() brings you here
this.loading = false;
this.error = err;
});
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 };
}