Async/Promises Practice

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.

There are some things you need to adjust. First, your last line should not invoke the functions, but simply pass them to matchPromises, like so (notice the removal of the paren pairs after each function name):

matchPromises(firstFunction, secondFunction)

Next, within matchPromises, you want to await a function call, not a function reference, so you should be calling your two functions (notice the appended parens to both lines):

    let firstFunctionResult = await firstFunction();
    let secondFunctionResult = await secondFunction();

Try those changes and see what happens.

1 Like