Correct way of catching error in Promise objects - angular-promise

Ok so I am newbie in Angularjs,one of my current task is to code a CRUD functionality and I used the Promise to handle it.
dao.updateEntityCharSpecUseRelSql = function (paramField) {
return new Promise(function (resolve, reject) {
.......
}).catch(err => { reject(err)});// **my PM says, catching error is wrong**
}
module.exports = dao;
First, I thought, catch block is just alright because I am getting it from the Promise object which returns the error if something goes wrong.
But my Pm says, in order to use this, promises should have .then() first.
Is it really a bad practice to use the catch() without then(). What he propose is that instead, I should create a try & catch block inside the Promise() something like
new Promise (function(resolve, reject){
try {
resolve(something)
}catch(err){
reject(err)
}
})
Please enlighten me for this.TIA

Let's do a step back.
When you create a new Promise() you are responsible to handle each success and failure case.
Who is calling your function (and getting your promise) is responsible to handle the response inside a then() callback, if the promise was successfully resolved, or a catch() callback, if the promise was rejected.
So, you don't need to catch your own promise.
Example:
function init() {
getAsyncValues()
.then(function (result) {
// it will do something based on his business logic
})
.catch(function (error) {
// it will do something based on his business logic
});
}
function getAsyncValues() {
return new Promise(function(resolve, reject) {
...
resolve(SOME_VALUES);
...
reject(SOME_ERRORS);
})
}
And if your "promise handler" need to call async task before resolving something, you can wait his resolution like:
const examplePromise = new Promise(fuction (resolve, reject) {
asyncTask() // executing an async task
.then(function(result) {
resolve(result);
})
.catch(function(error) {
reject(error)
});
})

Related

Promise Stays Pending, Returns Null

I am working on a GraphQL query where I am trying to find a unique model. However, nothing ever gets returned because the code kept carrying on before the query was finished, thus attempted to return a Promise when it expected a Model. The code looks as follows...
const findShift = async (date) => {
console.log("In mutation function")
const foundShift = await db.shift.findUnique({
where: {
date: date
}
})
return foundShift
}
const foundShift = findShift(date).then( resolved => {
console.log("printing resolved...")
console.log(resolved)
if (resolved.id != 'undefined'){
console.log({
id: resolved.id,
date: resolved.date,
allDevices: resolved.allDevices
})
return foundShift
}
else{
throw new Error("no shift of that date found!")
}
})
And the console.log statements make the console look as so...
In mutation function
Promise { <pending> }
prisma:info Starting a postgresql pool with 9 connections.
and ultimately the query just returns null. As you see, I tried using then and putting the mutation itself into an entirely different function just to circumvent these asynchronisity issues to no avail. Does anyone see a workaround?
First off, ALL async functions return a promise. The return value in the async function becomes the resolved value of that promise. So, the caller of an async function MUST use .then() or await to get the resolved value from the async function. There is no way to "circumvent" the asynchronicity like you are attempting. You can tame it to make it more usable, but you can't escape it. So, your async function returns a pending promise that will eventually resolve to whatever value you return inside your async function.
You can read more about how async functions work here in this other answer.
In trying to make a minimal, reproducible example of your code, I've reduced it to this where I've substituted an asynchronous simulation for the database call:
function delay(t, v) {
return new Promise(resolve => setTimeout(resolve, t, v));
}
// simulate asynchronous database operation
const db = {
shift: {
findUnique: function(data) {
return delay(100, { id: 123, date: Date.now(), allDevices: ["iPhone", "Galaxy", "Razr"] });
}
}
}
const findShift = async (date) => {
console.log("In mutation function")
const found = await db.shift.findUnique({
where: {
date: date
}
})
return found;
}
const date = Date.now();
const foundShift = findShift(date).then(resolved => {
console.log("printing resolved...")
console.log(resolved);
if (resolved.id != 'undefined') {
console.log({
id: resolved.id,
date: resolved.date,
allDevices: resolved.allDevices
})
return foundShift
} else {
throw new Error("no shift of that date found!")
}
});
When I run this in nodejs, I get this error:
[TypeError: Chaining cycle detected for promise #<Promise>]
And, the error is caused by this line of code:
return foundShift
You are attempting to return a promise that's already part of this promise chain from within the promise chain. That creates a circular dependency which is not allowed.
What you need to return there is whatever you want the resolved value of the parent promise to be. Since that looks like it's the object you construct right above it, I've modified the code to do that. This code can be run and foundShift is a promise that resolves to your object.
function delay(t, v) {
return new Promise(resolve => setTimeout(resolve, t, v));
}
// simulate asynchronous database operation
const db = {
shift: {
findUnique: function(data) {
return delay(100, { id: 123, date: Date.now(), allDevices: ["iPhone", "Galaxy", "Razr"] });
}
}
}
const findShift = async (date) => {
const found = await db.shift.findUnique({
where: {
date: date
}
})
return found;
}
const date = Date.now();
const foundShift = findShift(date).then(resolved => {
if (resolved.id != 'undefined') {
let result = {
id: resolved.id,
date: resolved.date,
allDevices: resolved.allDevices
};
return result;
} else {
throw new Error("no shift of that date found!")
}
});
// foundShift here is a promise
// to get it's value, you have to use .then() or await on it
foundShift.then(result => {
console.log("final result", result);
}).catch(e => {
console.log(e);
});
Here are a couple of rule about promises that might help:
All fn().then() or fn().catch() calls return a new promise that is chained to the one that fn() returned.
All async functions return a promise.
You cannot "circumvent" asynchronicity and somehow directly return an asynchronously retrieved value. You will have to use a callback, an event or return a promise (or some similar asynchronous mechanism) in order to communicate back to the caller an asynchronously retrieved value.
await can only be used inside an async function (or at the top level of an ESM module).
The first await in a function suspends execution of the async function and then immediately returns an unfulfilled promise to the caller. So, the await only affects the current function flow, not the caller's flow. The caller will still have to use .then() or await to get the value out of the promise that the async function returns.
Try as you might, there is no way around these rules (in Javascript as it currently runs in a browser or in nodejs).

Parse Cloud Code response is null after calling a function with callback

I have a cloud code from which I call an external function.
The cloud code response is null but the console displays the response
my cloud code ;
Parse.Cloud.define("testccadd", async request => {
try {
var ccaddrequest = {
conversationId: '123456789',
email: 'email#email.com',
};
externalFunction (ccaddrequest, function (err, result) {
console.log(result);
return result;
}) ;
} catch (e) {
console.log("Error");
}
});
console.log (result); shows the values from the external function, but the return result; returns null
how can I get the external function response as response of my cloud code function ?
The problem is that your externalFunction uses a callback to return its result. That is an asynchronous event, meaning that it happens after your cloud functions has been processed.
The cloud function will execute var ccaddrequest... and then call externalFunction but it won't "wait" for externalFunction to call the callback function if it contains asynchronous commands.
So you need to wrap the externalFunction in a Promise (see how to promisify callbacks) and then await the result of it.
Plus you need to return the result of the Promise, so in your code you need to add
Parse.Cloud.define("testccadd", async request => {
try {
var ccaddrequest = {
conversationId: '123456789',
email: 'email#email.com',
};
var result = await externalFunctionPromise(...);
return result;
} catch (e) {
console.log("Error");
}
});

redux asynchronous action with await/async

From the tutorial located here, I have a question regarding this section of the code:
export function fetchPosts(subreddit) {
// Thunk middleware knows how to handle functions.
// It passes the dispatch method as an argument to the function,
// thus making it able to dispatch actions itself.
return function (dispatch) {
// First dispatch: the app state is updated to inform
// that the API call is starting.
dispatch(requestPosts(subreddit))
// The function called by the thunk middleware can return a value,
// that is passed on as the return value of the dispatch method.
// In this case, we return a promise to wait for.
// This is not required by thunk middleware, but it is convenient for us.
return fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(
response => response.json(),
// Do not use catch, because that will also catch
// any errors in the dispatch and resulting render,
// causing an loop of 'Unexpected batch number' errors.
// https://github.com/facebook/react/issues/6895
error => console.log('An error occured.', error)
)
.then(json =>
// We can dispatch many times!
// Here, we update the app state with the results of the API call.
dispatch(receivePosts(subreddit, json))
)
}
}
Let's assume I wanted to use the async/await syntax instead of the "then" syntax, how would I get the error object if something fails?
e.g.
let response = await fetch(`https://www.reddit.com/r/${subreddit}.json`)
let json = await response.json();
I can surround these lines of code with a try/catch, but the author has a stern warning not to use catch here (refer to snippet above).
So is there a proper way to use the async/await pattern with this code?
In the link you provided the note to avoid using catch is regarding the promise .catch statement. This is because it would catch errors in both the then blocks. Instead of just errors caused via fetch or response.json() it would also catch errors caused via dispatch(receivePosts(subreddit, json))
You should be able to use async await as you describe in your post whilst avoiding catching errors caused by dispatch. e.g.
export function fetchPosts(subreddit) {
return async function (dispatch) {
dispatch(requestPosts(subreddit));
let response;
let json;
try {
response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
json = await response.json();
} catch(e) {
// handle fetch or json error here e.g.
dispatch(receivePostsError(subreddit, e.message));
}
if (json) {
dispatch(receivePosts(subreddit, json));
}
}
}

Asynchronous https firebase functions

Should HTTPS functions return asynchronous promises like realtime functions have to?
We haven't been returning in HTTPS functions (just using res.status.send etc), and it looks like firebase/function-samples aren't either. But the documentation is slightly ambiguous https://firebase.google.com/docs/functions/terminate-functions .
This works now in the latest Firebase:
exports.asyncFunction = functions.https.onRequest(async (request, response) => {
const result = await someAsyncFunction();
response.send(result);
});
HTTP functions currently do not respect returned promises - they require a sent result in order to terminate normally. If an HTTP function doesn't send a result, it will time out.
All other types of functions require a returned promise in order to wait for asynchronous work to fully complete.
If you don't have any async work to wait for, you can just return immediately.
These are the three cases outlined in the docs.
After much looking around , this is implementation with a Promise worked for me to return a value from a Google Cloud Function where the function needs to make a third-party asynchronous call :
exports.getSomeAccessToken = functions.https.onCall((data, context) => {
var dataStr = JSON.stringify(data, null, '\t');
console.log('ENTER [getSomeAccessToken], got dataStr: ' + dataStr);
return new Promise((resolve, reject) => {
gateway.clientToken.generate({}, function (err, gatewayResponse) {
var result = {
clientToken: gatewayResponse.clientToken
};
var resultStr = JSON.stringify(result, null, '\t');
console.log("resultStr : " + resultStr);
resolve(result);
});
});
});
Your cloud functions should return"end" with either of the following
res.redirect(), res.send(), or res.end()
What they mean by returning promises, is lets imagine you have a cloud function that updated a node in your realtime database, you would like to complete that work before responding to the HTTP request.
Example code
let RemoveSomething = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// Remove something
DoDatabaseWork()
.then(function (result) {
res.status(200).send();
})
.catch(function (err) {
console.error(err);
res.status(501).send();
});
});
});
Update: Added DoDatabaseWork example.
const DoDatabaseWork = function () {
return new Promise(function (resolve, reject) {
// Remove SomeNode
admin.database().ref('/someNode/').remove()
.then(function (result) {
resolve();
})
.catch(function (err) {
console.error(err);
reject();
});
});
}

Meteor async method call

I am very new to meteor and I have a method in Meteor.methods like :
sendStory(story) {
HTTP.call("GET", "https://offline-news-api.herokuapp.com/stories", function(error, response){
if(error){
console.log("error")
}else{
console.log(response)
var story = story
return story
}
})
}
and then I am calling this on my cliet like:
Meteor.call('sendStory', this.story, function(res){
console.log("some story")
console.log(res)
})
Here it is not printing the res value it is giving undefined and the api call is made at last..
How can I make api call first and then go to callback from api
Thank you ..
Well,
dont use the callback for http call like this:
sendStory(story) {
var story = HTTP.call("GET", "https://offline-news-api.herokuapp.com/stories");
return story;
}
refer here to Meteor Docs
You cannot return from a callback since Meteor methods run within fibers.
You could use a Future:
sendStory(story) {
Future = Npm.require('fibers/future');
var apiFuture = new Future();
HTTP.call("GET", "https://offline-news-api.herokuapp.com/stories", function(error, response){
if(error){
console.error("Error: ", error);
apiFuture.throw(error);
}else{
console.log("Response: ", response);
apiFuture.return(response);
}
});
return apiFuture.wait();
}
and on the client:
Meteor.call('sendStory', this.story, function(err, res){
console.log("some story");
if (err) {
console.error(err);
} else {
console.log("Great! A response from the API: ", res);
}
});
Like guns mentioned, you are returning undefined from server method. The method doesn't wait for the asynchronous function to terminate. Instead it returns.
In the server, I always go with synchronous approach.

Resources