-1

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' }

KHAN
  • 57
  • 7
  • 1
    "*the string "Passed" which is being returned by the .then function*" - no it isn't. `.then()` returns a promise. Do the `console.log` **inside** the `then` callback – Bergi Nov 22 '21 at 10:03

2 Answers2

1

You are intended to use promises this way:

p.then((x) => {
    console.log(x);
});

or this way (only works in async functions):

x = await p;

Normally, p would actually be a function that returns a promise, like this:

function p() {
    return new Promise((resolve, reject) => {
        resolve("message");
    });
}
GoldenretriverYT
  • 3,043
  • 1
  • 9
  • 22
1

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();
mr__pablo
  • 61
  • 1
  • 2