【问题标题】:Promise in the if statement (Javascript) [duplicate]if 语句中的承诺(Javascript)[重复]
【发布时间】:2018-10-17 03:08:12
【问题描述】:

我想在 if 语句中使用 Promise 结果,但是当我尝试这样做时,我得到了这样的结果:

const promise = new Promise((resolve, reject) => {
setTimeout(() => {
  resolve(5 * 2)
}, 1000)
})

console.log(promise.then(i => i) === 10) //false

在这种情况下是否有可能以某种方式等待提取承诺结果?

【问题讨论】:

  • console.log 放在then 回调中:promise.then(i => { console.log(i == 10); })。不,你不能立即得到布尔结果。

标签: javascript asynchronous promise


【解决方案1】:

您可以使用Async/Await 以更同步的方式使用它。

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(5 * 2)
  }, 1000)
});

(async () => {
  console.log(await promise === 10);
})();

【讨论】:

    【解决方案2】:

    您只能在传递给then 的函数中使用 Promise 的值 –

    const delay = x =>
      new Promise (r => setTimeout (r, 1000, x))
     
    delay (5*2) .then (console.log)
    // 10
    
    delay (5*2) .then (x => x === 10) .then (console.log)
    // true

    或者在 async 函数内部使用 await 关键字 –

    const delay = x =>
      new Promise (r => setTimeout (r, 1000, x))
     
    const main = async () =>
    { const x = await delay (5*2)
      console.log (x) 
      console.log (x === 10)
      return 'done'
    }
    
    main () .then (console.log)
    // 10
    // true
    // done

    【讨论】:

    • 在使用 async/await 时,您可以在传递给 then 的函数之外使用 Promise 的值。 example
    • @RaphaelRafatpanah 感谢提及await
    【解决方案3】:

    你需要在then内处理Promise的结果。

    console.log(promise.then(i => i === 10))
    

    这无论如何都会记录 promise 对象。如果要记录结果:

    promise.then(i => console.log(i === 10))
    

    为了更清楚,请参阅使用更多语法提示编写的 lambda:

    promise.then(    (i) => { console.log(i === 10); }    );
    

    甚至作为匿名函数:

    promise.then(   function(i){ console.log(i === 10); }  );
    

    在这里你预先准备好行为然后通过它:

    var myTimeoutHandler = function(i){
        console.log(i === 10); 
    };
    promise.then(myTimeoutHandler);
    

    i => ... 语法是它的简写。

    一般来说,使用 Promise(和 ReactiveX 的 Observable 类似),您正在对某些东西做出反应,因此您通过传递回调(此处以 lambda 的形式)来提供行为。因此,需要处理任何处理的每个操作都需要在回调中。

    阅读有关Promisethen 的更多信息。

    【讨论】:

      猜你喜欢
      • 2014-03-21
      • 2021-07-13
      • 1970-01-01
      • 2021-05-29
      • 2015-03-01
      • 2013-08-08
      • 2014-09-09
      • 2019-01-25
      • 1970-01-01
      相关资源
      最近更新 更多