I’ve been struggling with a question in https://www.codecademy.com/practice/tracks/introduction-to-javascript/modules/asynch-js!
Question:
Write an async
function, matchPromises()
. Your function should have two parameters—both functions that take no arguments and return promises. When invoked, matchPromises()
should invoke the two function arguments and compare the two promises:
- If the promises have the same resolved value,
matchPromises()
should return the string"match"
. - If the promises have different resolved values,
matchPromises()
should return the string"no match"
. - If either promise rejects,
matchPromises()
should return the string"error"
.
my solution is:
function firstFunction() {
let number = Math.floor(Math.random() * 10)
return new Promise(function(resolve, reject){
if (number > 5) {
resolve(number)
}
else {
reject(number)
}
})
};
function secondFunction() {
return new Promise(function(resolve){
resolve(Math.floor(Math.random() * 10))
})
};
async function matchPromises(firstFunction,secondFunction) {
let result;
try {
let firstFunctionResult = await firstFunction;
let secondFunctionResult = await secondFunction;
if ( firstFunctionResult === secondFunctionResult) {
result = 'match';
}
else {
result = 'no match'
};
} catch(error) {
result = 'error'
};
console.log(result);
return result;
}
matchPromises(firstFunction(),secondFunction())
I’m probably misreading the question or overcomplicating things, but I can’t get passed this question, even though the console.log()
shows that it’s working as per the spec.