【问题标题】:resolving a promise created by then?解决那时创建的承诺?
【发布时间】:2017-01-08 15:53:02
【问题描述】:
 return Promise.resolve(member + 2).then((result) => {return result + 2});

原始承诺已解决,then 创建了新承诺?那么现在第二个 promise 的值是 result + 2 但仍然处于未决状态?我该如何解决?

【问题讨论】:

  • 第二个then?我只看到一个then...
  • @LarsH,是的,我指的是那个。
  • then 返回的 Promise is 已解决 ... 除非 then 返回的值是 Promise,否则 .then 返回的 Promise “采用”返回的 Promise跨度>
  • 我认为Promise.resolve这个名字让很多人感到困惑;它不会强制同步评估或类似的东西;它只是一种从值创建“已解决”(成功)承诺的方法。
  • but is still pending - 因为.then 是异步的,所以它处于挂起状态

标签: javascript node.js


【解决方案1】:

承诺总是异步评估,这意味着不可能将承诺“解析”回同步环境。访问Promise 值的唯一方法是在thencatch 回调中。

Promise.resolve(10)
       .then(result => result + 2)
       .then(result => console.log(result));

【讨论】:

    【解决方案2】:
     var x =Promise.resolve(10 + 2).then((result) => {return result+2});
         x.then((value)=>console.log(value));
    
    // 14
    

    【讨论】:

      【解决方案3】:

      你应该调用 then() 来获得新的结果:

      let promise = Promise.resolve(17).then(res => res + 2000);
      
      promise.then(newRes => {
        console.log("newRes",newRes) // 2017
      })
      

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-26
        • 1970-01-01
        • 1970-01-01
        • 2015-06-24
        • 2015-09-13
        • 2014-08-08
        • 1970-01-01
        相关资源
        最近更新 更多