【问题标题】:How can i use promises to get the valueHow can i use promises to get the value
【发布时间】:2022-12-27 23:59:54
【问题描述】:

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}));

【问题讨论】:

    标签: javascript promise


    【解决方案1】:

    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() issynchronous, while Promise has anasynchronousnature, 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) => console.log(val));

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2023-01-31
      • 2022-12-01
      • 2022-12-01
      • 2022-12-01
      • 2022-12-28
      • 2022-12-27
      • 2022-12-02
      • 2022-12-26
      相关资源
      最近更新 更多