Simple Promise Example Needed

I recently came across this question on an application:

Write a javascript function checkString(foo) which takes a parameter `foo`. The function should return a Promise that resolves if `foo` is equal to "hello", otherwise the Promise should reject. Below this function, write code that invokes checkString() and outputs (in the console) "Good!" upon Promise success or "Bad!" upon Promise failure. Do not use jQuery.

and I was unable to complete this.

Can anyone show me how I would have successfully coded this?

Thank you. I want to be prepared next time.

Regards,

John
John S.Web DeveloperAsked:
Who is Participating?
 
SwapnilConnect With a Mentor Software ArchitectCommented:
Here you go. Try below in jsfiddle.net

function successCallback(result) {
  console.log("Success " + result);
}

function failureCallback(error) {
  console.log("Failure " + error);
}
function checkString(foo) {
	return new Promise(function(resolve,reject) {
			if(foo == 'hello')
      resolve('Good!');
      else
				reject('Bad!');
     });
}

checkString('hello').then(successCallback, failureCallback);
checkString('hellod').then(successCallback, failureCallback);

Open in new window

1
 
John S.Web DeveloperAuthor Commented:
Worked perfect. Brilliant, thanks!
0
 
John S.Web DeveloperAuthor Commented:
This solution landed me an interview! ( I will need you to be available on Monday at 9am for emergency answers if they quiz me more ) LMAO
1
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.