0

I playing around with something like this

function myFunc(){
    var val = 10;
    new Promise(function(resolve,reject){
    setTimeout(function(){
        //
      val = 20;
      resolve();
    },1000)
  }).then(function(){
    return val;
  })
}

var val = myFunc();
console.log(val);

Here I'm expecting 20 in output but getting undefined. What's wrong here ?

Fiddle link: https://jsfiddle.net/nvLc60bm/

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Osman Rafi
  • 938
  • 1
  • 16
  • 37
  • 1
    Problems: 1. `myFunc` doesn't return anything. 2. Returning `val` from the callback function of `then` method does not make it a return value of the outer function. 3. If you return the promise from the `myFunc` function, you need to either `await` or chain a `then` method to the `myFunc` function call. – Yousaf May 21 '21 at 09:45
  • can you play around it here https://jsfiddle.net/nvLc60bm/ ? – Osman Rafi May 21 '21 at 11:44
  • 1
    [Try this code](https://pastebin.com/LxjD2TSs) – Yousaf May 21 '21 at 17:39

0 Answers0