Skip to content Skip to sidebar Skip to footer

Return A Non Promise Value From A Function Involving Promises

I have a function called 'test_sheet' that is supposed to return a value. that value will then be passed to a tester function which will tell me if I passed or failed the test. in

Solution 1:

Well, technically it is possible, tester() may reamain intact:

var test_sheet=false;
functionstart_test()
{
   //all my logic will go herenewPromise(function(resolve, reject)
   {
      //simulating an async operationsetTimeout(() =>resolve(true), 1000);
   })
   .then(res => {
      test_sheet=true;
      tester();
   });
}

functiontester()
{
   //not allowed to change this function in any way
   test_sheet == true ? console.log("pass!") : console.log("fail!");
}

//tester();start_test();

But the test starts with start_test() now, and test_sheet became a variable, with the sole purpose of acting as an argument - which could not be added to testing() without modifying it. A nonworking bad design is transformed to working bad desing this way.

Solution 2:

test_sheet() always returns a promise so try to get it resolved using async await or .then which feeds into the tester() function.

call you function this way:

test_sheet().then(function(test_sheet){
tester(test_sheet)})

for this you need to pass the boolean return value from test_sheet() to tester(test_sheet)

Solution 3:

If you handle asynchronous code you have to use promise or callback and handle with async/await to change them to synchronous code

For example

functiontest_sheet()
{
   //all my logic will go herereturnnewPromise(function(resolve, reject) {
      //simulating an async operationsetTimeout(() =>resolve(true), 2000);
   })
}

asyncfunctiontester()
{
   //not allowed to change this function in any wayawaittest_sheet() == true ? console.log("pass!") : console.log("fail!");
}

tester();

Post a Comment for "Return A Non Promise Value From A Function Involving Promises"