簡體   English   中英

如何理解這個Promise代碼?

[英]How to understand this Promise code?

'use strict';

Promise.resolve(() => 'John')
  .then((args) => {
    console.log(args);
    throw new Error('ops')
  })
  .catch((ex) => {
    console.log(ex)
  })
  .then(() => {
    throw new Error('ups')
    console.log('Doe')
  })

我認為console.log(args); 應該輸出'John' ,但是當我運行這段代碼時,輸​​出是[ [Function] ]

所以我很困惑。

Promise.resolve將使用您傳遞給它的值創建一個新的Promise。 因此,在您的情況下,您的承諾實際上是通過函數對象解決的。 這意味着, then處理程序將傳遞給函數對象本身。

你應該做的是

new Promise((resolve, reject) => resolve('John'))
  .then(args => {
    console.log(args);
    throw new Error('ops')
  })
  .catch(console.log.bind(console));

現在,您正在創建一個Promise對象,並且您正在使用值John解析它。


如果你希望你的Promise很容易被一個值解析,那么不要傳遞函數對象,而是將實際值本身傳遞給Promise.resolve函數。

Promise.resolve('John')
  .then(args => {
    console.log(args);
    throw new Error('ops')
  })
  .catch(console.log.bind(console));

現在,你有一個Promise,用值John解析, then處理程序將獲得已解析的值John

注意:當您知道實際解決方法時,這是創建Promise的推薦方法,這樣您就可以避免Promise構造函數反模式

'use strict';

Promise.resolve('John')
  .then((args) => {
    console.log(args);
    throw new Error('ops')
  })
  .catch((ex) => {
    console.log(ex)
  })
  .then(() => {
    throw new Error('ups')
    console.log('Doe')
  })

我修改了Promise.resolve('John') ,它有效。 請參閱Promise.resolve

resolve用於將參數直接傳遞給then-handler

如果你想要'John',你需要在你的調用中調用匿名函數來解析()

Promise.resolve(function(){return 'John';}());

注意}()函數調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM