1

I have tried this but gives me a promise I just want do it like this.

function doSome() {
  return new Promise(
    function(res, rej) {
      let d = [];
      for (var i = 0; i < 100; i++) {
        d.push(i)
      }
      res(d)
    })

}
console.log(doSome().then((val)=>{return val}));
John Delvin
  • 53
  • 1
  • 8
  • 2
    Your function is returning a promise. You must use either `.then()` or `await` on that promise to get the resolved value of the promise. I hope you realize that a promise is not necessary at all here because there is no asynchronous code. You could just return `d` directly without using a promise. A promise is only helpful when you want to be notified when an asynchronous operation has completed. Your `for` loop is entirely synchronous and thus has no benefit from using a promise - in fact the promise just makes the code more complicated than necessary to use. – jfriend00 Dec 27 '22 at 15:49
  • Just *don't* use promises and you'll get the actual value? – Bergi Dec 27 '22 at 17:07

2 Answers2

2

The provided code will not print the expected output because you're trying to console.log() the Promise itself rather than its value. Since console.log() is synchronous, and Promise has an asynchronous nature, the issue can be solved by moving the logging into .then block:

function doSome() {
  return new Promise(
    function(res, rej) {
      let d = [];
      for (var i = 0; i < 100; i++) {
        d.push(i)
      }
      res(d)
    })

}

doSome()
  .then((val) => { return val })
  .then((val) => {
    // Do something
    console.log(val);
  });
P.S.
  • 15,970
  • 14
  • 62
  • 86
  • Also [drop the pointless `.then(value => value)`](https://stackoverflow.com/q/41089122/1048572)! – Bergi Dec 27 '22 at 17:08
  • I am thinking this answer is wrong. Your question answer looks like: https://stackoverflow.com/a/39914235/9309919 anyway, your choice :) – Murat Çakmak Dec 27 '22 at 20:24
  • @MuratÇakmak The thing that looks like a synchronous `sleep` is the part of the code taken from the OP. Your own answer has the very same problem. – Bergi Dec 27 '22 at 21:19
0

You can use await. Because promise is a async

function doSome() {
    return new Promise((resolve , reject) => {
        let d = [];
        for (var i = 0; i < 100; i++) {
        d.push(i)
        }
        resolve(d)         
    });
}

//way to main function
async function main() {
    console.log(await doSome());
}
main();

//directly
(async () => {
    console.log(await doSome());    
})();
Murat Çakmak
  • 151
  • 2
  • 7