Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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");
    });
}
about 4 years ago · Juan Pablo Isaza Report

0

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();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!