Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I am new to JavaScript promise and async. I am having problem to get the correct value from the "TrueOrFalsefn()" show below,

JavaScript
// Objective: to return True/False from this function 
// 
function TrueOrFalsefn(){    
    var output = null;      
    //1. Create a new function that returns a promise
    if (secondFunction()== true)
	{
		alert("Yes"); 
		return true;  // <<--- 
	}
	else if (secondFunction()== false)
	{
		alert("No");
		return false;    
	}
     
	//2. Create an async function
    async function secondFunction() { 
        let result2 = await firstFunction()
		 if (result2==101 )
		 {
			 output = true;  
		 }
		 else{
			output = false;
		 }
         return output;
    }; 

	function firstFunction() {
      return new Promise((resolve, reject) => {
          let y = 100
          setTimeout(() => {           
             resolve(y+1)
          }, 2000)
      })
    }
}


What I have tried:

When debug in browser, result is always "null" but I am expecting "True" in return.

Can anyone advise how can I get it right?
Thanks in advance
Wilson
Posted
Updated 1-Oct-20 1:04am
v2

1 solution

The result of an async function will be a Promise. You either need to await it, or use the continuation to read the result.

You should also avoid calling the function twice. Call it once and store the result in a variable.
JavaScript
async function TrueOrFalsFn(){
    function firstFunction(){
        return new Promise((resolve, reject) => {
            let y = 100
            setTimeout(() => resolve(y + 1), 2000)
        });
    }
    
    async function secondFunction(){
        let result2 = await firstFunction();
        return result2 === 101;
    }
    
    let output = await secondFunction();
    if (output) {
        alert("Yes");
    }
    else {
        alert("No");
    }
    
    return output;
}
NB: The calling code will also need to await the result of this function, or use the continuation to read the result.
 
Share this answer
 
Comments
CoderWil 1-Oct-20 22:45pm    
Thank you very much, Richard. This is great, I have got it right using your approach.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900