Search code examples
javascriptasynchronouspromisees6-promise

How can we store the values resolved by a JavaScript Promise?


I am currently learning async JavaScript, and I am confused about how to get the values retured by a promise my code:

let p  = Promise.resolve("Passed")

let x = p.then(msg=>msg).catch(msg=>msg)
setTimeout(()=>console.log(x), 2)
console.log(x)

Output:

Promise { <pending> }
Promise { 'Passed' }

How can I get the string "Passed" which is being returned by the .then function, and why the promise is pending even when the Promise is resolved? But when we console.log its value using a setTimeout function is gives its value, and How to get the "Passed" from Promise { 'Passed' }


Solution

  • You cannot get a response out of promise right now. To solve you can use 2 approaches:

    subscribe inside of then with a new function which gets the promise result // but it would be asynchronously like this

    var p = Promise.resolve([1,2,3]);
    p.then(function(v) {
      console.log(v[0]); // 1
    });
    

    second one is : use async function with await structure

    async function f() {
    
      let promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("done!"), 1000)
      });
    
      let result = await promise; // in this part it will be wait until promise will end its work
    
      alert(result); // "done!"
    }
    
    f();