Promise reject doesn't propagate the error correctly - javascript

I receive a complex object, let's say it will look like this:
complexObject: {
fruits: string[],
vegetables: string[],
milk: [] | [{
expirationDate: string,
quantity: string
}]
}
So, the logic is, that when I receive an empty object (milk will be just []), the verifyObject method will return undefined (the further logic is more complex and has to receive undefined...); the same case will be when the method will be called with an empty/undefined object.
The only verification, for the milk, should be like this:
If we have milk, then it needs to have both quantity and expirationDate, else it should return false.
The problem is, that when I send an object like this:
{
'fruits': ['apples', 'bananas'],
'vegetables': ['tomatoes'],
'milk': [{
'quantity': '10'
}]
}
in the checkAndAssign method it will see, the error, print the console.log, but it won't stop there and it will add the object to the result.
Also, in the verifyObject method, it will enter catch block, but upper it won't throw the error and it will resolve the promise instead, returning the result...
I want to stop the execution when I receive a wrong message and propagate the error...
This is the code:
verifyObject(complexObject) {
return new Promise((resolve, reject) => {
const result = {};
const propertiesEnum = ['fruits', 'vegetables', 'milk'];
if (!complexObject) {
resolve({ result: undefined });
} else {
this.checkAndAssign(complexObject, result)
.catch((err) => {
console.log('enter error');
reject({ message: err });
})
if (!Object.keys(result).length) {
console.log('resolve with undefined');
resolve({ result: undefined });
}
console.log('resolve good');
resolve({ result });
}
})
}
private checkAndAssign(complexObject, result) {
return new Promise((resolve, reject) => {
for (const property of complexObject) {
if(complexObject[property] && Object.keys(complexObject[property]).length)
if(property === 'milk' && this.verifyMilk(complexObject[property]) === false) {
console.log('rejected');
reject('incomplete');
}
Object.assign(result, {[property]: complexObject[property]})
console.log('result is...:>', result);
}
console.log('final result:>', result);
resolve(result);
});
}
private verifyMilk(milk:any): boolean {
for(const item of milk) {
if(!(item['expirationDate'] && item['quantity'])) {
return false;
}
}
return true;
}

Calling reject doesn't terminate the function you call it from. reject is just a normal function call. Once the call is complete, the function calling it continues.
If you don't want that, use return:
private checkPropertyAndAssignValue(complexObject, result) {
return new Promise((resolve, reject) => {
for (const property of complexObject) {
if(complexObject[property] && Object.keys(complexObject[property]).length)
if(property === 'milk' && this.verifyMilk(complexObject[property]) === false) {
console.log('rejected');
reject('incomplete');
return; // <================================================ here
}
Object.assign(result, {[property]: complexObject[property]})
console.log('result is...:>', result);
}
console.log('final result:>', result);
resolve(result);
});
}
Then verifyObject needs to wait for the fulfillment of the promise from checkPropertyAndAssignValue. verifyObject's code falls prey to the explicit promise creation anti-pattern: It shoudln't use new Promise, because it already has a promise from checkPropertyAndAssignValue. Avoiding the anti-pattern also helps avoid this error:
verifyObject(complexObject) {
const result = {};
const propertiesEnum = ['fruits', 'vegetables', 'milk'];
if (!complexObject) {
return Promise.resolve({ result: undefined });
}
return this.checkPropertyAndAssignValue(complexObject, result)
.then(() => {
if (!Object.keys(result).length) {
console.log('resolve with undefined');
return { result: undefined };
}
console.log('resolve good');
return { result };
})
.catch((err) => {
console.log('enter error');
throw { message: err }; // *** Will get caught by the promise mechanism and turned into rejection
});
}
As an alternative: If you're writing this code for modern environments, you may find async functions and await to be more familiar, since they use the same constructs (throw, try, catch) that you're used to from synchronous code. For example:
async verifyObject(complexObject) {
const result = {};
const propertiesEnum = ['fruits', 'vegetables', 'milk'];
if (!complexObject) {
return { result: undefined };
}
try {
await this.checkPropertyAndAssignValue(complexObject, result);
// ^^^^^−−−−− waits for the promise to settle
if (!Object.keys(result).length) {
console.log('return undefined');
return { result: undefined };
}
console.log('return good');
return { result };
} catch (err) {
console.log('enter error');
throw { message: err }; // *** FWIW, suggest making all rejections Error instances
// (even when using promises directly)
}
}
private async checkPropertyAndAssignValue(complexObject, result) {
// *** Note: This used to return a promise but didn't seem to have any asynchronous
// code in it. I've made it an `async` function, so if it's using something
// that returns a promise that you haven't shown, include `await` when getting
// its result.
for (const property of complexObject) {
if(complexObject[property] && Object.keys(complexObject[property]).length)
if(property === 'milk' && this.verifyMilk(complexObject[property]) === false) {
throw 'incomplete'; // *** FWIW, suggest making all rejections Error instances
// (even when using promises directly)
}
Object.assign(result, {[property]: complexObject[property]})
console.log('result is...:>', result);
}
console.log('final result:>', result);
return result;
}

Related

Mongoose function returning before Promise resolved

mongoCheckFile = async (fileData) => {
try {
let offerIdsValues = [];
//Extract all fileIds from CSV
fileData.data.forEach((element, idx, fileData) => {
fileIdsInCsv.push(`${element.fileId}`)
});
fileData.fileOffers.forEach(element => {
offerIdsValues.push(element.id);
});
let matchingClickDocs = [];
//The following functions are not waited for before returning
await Click.find({
$and: [ {fileId: { $in: fileIdsInCsv} }, { fileId: {$in: offerIdsValues} } ]
}).populate('furtherInfo').exec(async (error, clicks) => {
if (error) {
console.log(error);
} else {
await Promise.all(clicks.map(async (click) => {
const furtherDatas = await furtherData.findOne({ fileId: click.fileId });
if (furtherDatas) {
click.furtherInfo = furtherDatas;
await click.save();
matchingClickDocs.push(click);
//this pushes correct values and creates correct array.
}
}));
console.log(matchingClickDocs.length, 'first')
// This returns after global function with correct val
}
console.log(matchingClickDocs.length, 'second')
// This returns after above with correct val
});
console.log( matchingClickDocs.length, 'third')
// Returns first with incorrect Val.
}
catch (err) {
return (err);
}
};
This function returns before the promise returns its array.
I have console.logged the output as I run through and its all good until it comes to returning it.
I've hit a brick wall trying to return these values before the function returns.
I guess its a problem with the global function not awaiting the promises at the end.
I've tried a few different implementations but keep getting stuck on it.

TypeScript: Error inside Promise not being caught

I am developing a SPFx WebPart using TypeScript.
I have a function to get a team by name (get() returns also a promise):
public getTeamChannelByName(teamId: string, channelName: string) {
return new Promise<MicrosoftGraph.Channel>(async (resolve, reject) => {
this.context.msGraphClientFactory
.getClient()
.then((client: MSGraphClient) =>{
client
.api(`/teams/${teamId}/channels`)
.filter(`displayName eq '${channelName}'`)
.version("beta")
.get((error, response: any) => {
if ( response.value.length == 1) {
const channels: MicrosoftGraph.Channel[] = response.value;
resolve(channels[0]);
} else if (response.value.length < 1) {
reject(new Error("No team found with the configured name"));
} else {
reject(new Error("Error XY"));
}
});
})
.catch(error => {
console.log(error);
reject(error);
});
});
}
I call this function like this:
public getConversations(teamName: string, channelName: string, messageLimitTopics: number = 0, messageLimitResponses: number = 0) {
return new Promise<any>(async (resolve, reject) => {
try {
this.getTeamGroupByName(teamName)
.then((teamGroup: MicrosoftGraph.Group) => {
const teamId: string = teamGroup.id;
this.getTeamChannelByName(teamId, channelName)
.then((teamChannel: MicrosoftGraph.Channel) => {
const channelId: string = teamChannel.id;
this.getChannelTopicMessages(teamId, channelId, messageLimitTopics)
.then((messages: MicrosoftGraph.Message[]) => {
const numberOfMessages = messages.length;
... // omitted
});
});
});
} catch(error) {
reject(error);
}
});
}
And this getConversations() function itself is called from my webpart code:
public getConversations() {
if (this.props.teamName && this.props.teamName.length > 0 &&
this.props.channelName && this.props.channelName.length > 0) {
GraphService.getConversations(this.props.teamName, this.props.channelName, this.props.messageLimitTopics, this.props.messageLimitResponses)
.then((conversations) => {
.. // omitted
})
.catch((err: Error) => {
console.log(err);
this.setState({errorMessage: err.message});
});
} else {
// Mandatory settings are missing
this.setState({errorMessage: strings.MandatorySettingsMissing});
}
}
So, as you can see, above, I want to write out the error (message) I receive from the reject inside the getConversations() functions. The problem is, that I don't receive this rejection with the error, but in the console I see the following:
Uncaught Error: No team found with the configured name
I added the .catch() blocks you see above inside getTeamChannelByName() but this doesn't get hit during debugging.
Haven't worked much with promises and I am still confused a bit about them, so I guess that I probably have constructed the promise chain wrongly, maybe placed the catch block(s) in the wrong position(s)?
I had a look at common mistakes done with Promises and I certainly had what is called a "Promise Hell".
So, I am not 100% sure yet, but I guess, the result of this was that there was no catch block for my .then("Promise") so the rejection went to nowhere.
I have now changed the calling method to this, and I also removed the try/catch blocks, as it is unnecessary:
public getConversations(teamName: string, channelName: string, messageLimitTopics: number = 0, messageLimitResponses: number = 0) {
return new Promise<any>(async (resolve, reject) => {
let teamId: string = null;
let channelId: string = null;
this.getTeamGroupIdByName(teamName)
.then(tId => {
teamId = tId;
return this.getTeamChannelIdByName(teamId,channelName);
})
.then(cId => {
channelId = cId;
return this.getChannelTopicMessages(teamId, channelId, messageLimitTopics);
})
.catch(error => {
reject(error);
});
});
}

How can i rewrite these JavaScript promises to be less complicated?

I wrote this, but it looks rough, its for node js so all values need to be gotten in order
import tripfind from '../model/tripfind';
import addbook from '../model/addbook';
import bookfind from '../model/bookfind';
function addBook(info) {
return new Promise((resolve, reject) => {
let rowcount = -1;
bookfind(0, -1, -1).then((result) => {
if (result) {
rowcount = result.rowCount;
} else {
rowcount = 0;
}
tripfind(info.trip_id, 0).then((xresult) => {
let val = '';
if (xresult === 'false') {
val = 'trip is not valid';
resolve(val);
} else {
addbook(info, rowcount).then((value) => {
if (value === 'invalid id') {
resolve('invalid id');
}
resolve(value);
}).catch((err) => {
if (err) {
reject(err);
}
});
}
}).catch((error) => {
reject(error);
});
}).catch((err) => {
if (err) {
reject(err);
}
});
});
}
export default addBook;
thats the code above, the code also gets exported and is handled as a promise function, please help if you can
Without using async / await, this example is functionally equivalent to what you had before:
function addBook (info) {
return bookfind(0, -1, -1).then(result => {
const { rowCount } = result || { rowCount: 0 };
return tripfind(info.trip_id, 0).then(trip =>
trip === 'false'
? 'trip is not valid'
: addbook(info, rowCount)
);
});
}
Sections like
.then((value) => {
if (value === 'invalid id') {
resolve('invalid id');
}
resolve(value);
})
.catch((err) => {
if (err) {
reject(err);
}
});
.catch((error) => {
reject(error);
});
are completely superfluous, so removing them doesn't affect the logic at all. After removing those, and unwrapping your Promise constructor antipattern, you can see the logic becomes a lot more simplified.
You're missing some returns of promises, and if you like this way of writing you should indent then() and catch() in the same way. Also doing this
.catch((err) => {
if (err) {
reject(err);
}
});
is useless, caus you catch an error to reject it. Rewritten in promise pattern (and a bit of optimization):
function addBook(info) {
return bookfind(0, -1, -1)
.then((result) => {
rowcount = result ? result.rowCount : 0
return tripfind(info.trip_id, 0)
.then((xresult) => {
if (xresult === 'false') {
return 'trip is not valid'
}
return addbook(info, rowcount)
})
})
}
Anyway is more clear with the async/await pattern:
async function addBook(info) {
let result = await bookfind(0, -1, -1)
rowcount = result ? result.rowCount : 0
let xresult = await tripfind(info.trip_id, 0)
if (xresult === 'false')
return 'trip is not valid'
let value = await addbook(info, rowcount)
return value
}
like this?
function addBook(info) {
return bookfind(0, -1, -1).then((result) => tripfind(info.trip_id, 0)
.then((xresult) => (xresult === 'false') ?
'trip is not valid' :
addbook(info, result ? result.rowCount : 0)
)
);
}
or with async/await
async function addBook(info) {
const result = await bookfind(0, -1, -1);
const xresult = await tripfind(info.trip_id, 0)
return xresult === "false"?
'trip is not valid' :
addbook(info, result ? result.rowCount : 0);
}
Avoid the Promise/Deferred antipattern: What is the explicit promise construction antipattern and how do I avoid it?
and remove pointless/useless code, like this function for example:
(value) => {
if (value === 'invalid id') {
resolve('invalid id');
}
resolve(value);
}
which always resolves to value. that's like return value === 1? 1: value
Or all the (error) => { reject(error); } just to "forward" the error to the returned promise.
or this construct
let rowcount = -1;
//....
if (result) {
rowcount = result.rowCount;
} else {
rowcount = 0;
}
//....
doSomethingWith(rowcount)
which can be summed up as doSomethingWith(result ? result.rowCount : 0)
A lot of people might tell you that async/await will solve this better. I think the problem is more about how the promises are used. If you have access to change the functions you are calling here's what I'd recommend.
Have functions return things of the same shape - e.g., the call to bookfind can return a rejected promise or a resolved promise that wraps undefined or {..., :rowcount:12}. If we remove the undefined result and return a default {..., rowcount:0 } it would simplify the calling functions substantially and contain logic a bit better.
Remove the superfluous function calls (.catchs and the addbook .then bit)
Here's what those functions could look like (not knowing your setup at all)
function tripfind(id, num) {
return new Promise(function(resolve, reject) {
doSomething(function(err, results) {
if (err) return reject(err);
if (results === "false") return reject(new Error("trip is not valid"));
return resolve(results);
});
});
}
function bookfind(id, start, end /*or whatever*/) {
return new Promise(function(resolve, reject) {
findBooks(function(err, results) {
if (err) return reject(err);
// handle odd cases too
if (!results) return resolve({ rowcount: 0 });
return resolve(results);
});
});
}
and the usages
bookfind(0, -1, -1).then(results =>{}).catch(err=>{})
tripfind(id, 0).then(results =>{}).catch(err=>{})
Using Promises this way, we don't have to check the value of results because if it wasn't there, the promise shouldn't resolve. Likewise, the shape of the thing coming out of the promise should always be the same. (I call it a smell when a function returns String|Object|Undefined, it's possible but I'd look hard at it first)
Using this pattern and removing calls that don't do anything (all the .catch calls), we can simplify the code down to:
function addBook(info) {
return bookfind(0, -1, -1).then(({ rowcount }) =>
tripfind(info.trip_id, 0).then(() =>
addbook(info, rowcount)
)
);
}

Rejecting Promise if many error sources

Im in situation where I have many potential error sources. Is there an elegant solution to this mess?
How should I reject it?
function myFuction(hash) {
return new Promise((resolve, reject) => {
// this could return error
const id = atob(hash);
// this could return error
let data = firstFunction(id);
// return error if not true
if (data && data.id) {
// this could return error
return secondFunction(data.id)
.then(item => {
// return error if not true
if (item) {
// this could return error
return thirdFunction(item)
.then(payload => {
resolve('OK');
});
}
});
}
});
}
Avoid the Promise constructor antipattern! You can use early returns with Promise.reject or just throw errors:
function myFuction(hash) {
return Promise.resolve().then(() => {
// this could throw error
const id = atob(hash);
// this could throw error
let data = firstFunction(id);
// return error if not true
if (!data || !data.id)
return Promise.reject(new Error("…")); // alternative: throw new Error("…");
return secondFunction(data.id);
}).then(item => {
// return error if not true
if (!item)
return Promise.reject(new Error("…")); // same here
return thirdFunction(item);
}).then(payload => 'OK');
}
(Additionally I applied some flattening, but as long as your always return from promise callbacks you could nest as well)

Using throw in promises

I would like to create a function that returns a promise and if something throws an error within, it returns promise reject.
function promiseFunc(options) {
return new Promise(() => {
return options;
});
}
function myfunc(options) {
return new Promise(() => {
if (!options) throw new Error("missing options");
return promiseFunc(options).then((result) => {
if (result.throwerr) throw new Error("thrown on purpose");
return result.value;
});
});
};
My test as follows:
const myfunc = require("./myfunc");
describe('myfunc', () => {
it('should fail without options', () => {
return myfunc()
.then((result) => { throw new Error(result) }, (err) => {
console.log("test #1 result:", err.message === "missing options");
});
});
it('should fail on options.throwerr', () => {
return myfunc({throwerr: true})
.then((result) => {}, (err) => {
console.log("test #2 result:", err.message === "thrown on purpose");
});
});
it('should return options.value', () => {
return myfunc({value: "some result", throwerr: false})
.then((result) => {
console.log("test #3 result:", result === "some result");
}, (err) => {});
});
});
The first test pass, but the second and third fails.
Log #2 does not even run, so I assumed the "throw on purpose" messes up something, therefore I created test #3, where I don't throw anything, but it still fails.
What am I missing?
Solution:
function promiseFunc(options) {
return new Promise(resolve => {
return resolve(options);
});
}
function myfunc(options) {
return new Promise((resolve, reject) => {
if (!options) throw new Error("missing options");
return promiseFunc(options).then(result => {
if (result.throwerr) throw new Error("thrown on purpose");
return resolve(result.value);
}).catch(err => {
return reject(err);
});
});
};
You forgot to pass a function with resolve and reject parameters, so your promises just don't work.
function promiseFunc(options) {
return new Promise(resolve => { // resolve function
resolve(options)
})
}
module.exports = function myfunc(options) {
return new Promise((resolve, reject) => { // since you may either resolve your promise or reject it, you need two params
if (!options) {
return reject(new Error("missing options"))
}
return promiseFunc(options).then(result => {
if (result.throwerr) {
return reject(new Error("thrown on purpose"))
}
resolve(result.value)
})
})
}
... and the test (mocha)
const assert = require('assert'),
myfunc = require("./myfunc")
describe('myfunc', () => {
it('should fail without options', done => { // mind the callback, promises are always async
myfunc()
.catch(err => {
assert(err.message === "missing options")
done() // <- called here
})
})
it('should fail on options.throwerr', done => {
myfunc({throwerr: true})
.catch(err => {
assert(err.message === "thrown on purpose")
done()
})
})
it('should return options.value', done => {
return myfunc({value: "some result", throwerr: false})
.then(result => {
assert(result === "some result")
done()
})
})
})
I would like to create a function that returns a promise and if something throws an error within, it returns promise reject.
This will do it ...
var q = require('q'); // In recent versions of node q is available by default and this line is not required
function iReturnAPromise(num) {
var def = q.defer();
if (typeof num=== 'number') {
try {
var value = 100 / num;
def.resolve(value);
} catch(e) {
def.reject("oops a division error - maybe you divided by zero");
}
} else {
def.reject("o no its not a number");
}
return def.promise;
}
PS this function was coded freehand and has not been tested - but this will work. Obviously try catch should be used sparingly.
PS I prefer the q library implementation of promise instead of the default node promise library - they take a very different approach. q dispenses with all the wrapping!
using the promise library u wanted ...
function iReturnAPromise(num) {
return new Promise(function(resolve, reject) {
if (typeof num === 'number') {
try {
var value = 100 / num;
resolve(value);
} catch (e) {
reject("oops a division error - maybe you divided by zero");
}
} else {
reject("o no its not a number");
}
})
}
iReturnAPromise(7).then(
function(response) {console.log("success", response)},
function(response) {console.log("failure", response)}
);
// Unexpectedly this is not an error in node 5.6 because div by 0 is not an error operation anymore!
iReturnAPromise(0).then(
function(response) {console.log("success", response)},
function(response) {console.log("failure", response)}
);
iReturnAPromise("fred").then(
function(response) {console.log("success", response)},
function(response) {console.log("failure", response)}
);
you can see why i prefer the q syntax :)

Categories

Resources