Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day153:Promise.resolve(obj),obj 有几种可能 #967

Open
Genzhen opened this issue Oct 10, 2020 · 1 comment
Open

Day153:Promise.resolve(obj),obj 有几种可能 #967

Genzhen opened this issue Oct 10, 2020 · 1 comment
Labels
JavaScript teach_tag

Comments

@Genzhen
Copy link
Collaborator

Genzhen commented Oct 10, 2020

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案
二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

@Genzhen Genzhen added the JavaScript teach_tag label Oct 10, 2020
@luuman
Copy link

luuman commented Nov 1, 2021

1.参数是一个Promise实例
如果参数是Promise实例,那么Promise.resolve将不做任何修改,原封不动地返回这个实例。

2.参数是一个thenable对象
thenable对象指的是具有then方法的对象,比如下面这个对象。

let thenable = {
	then: function(resolve, reject){
	  resolve('ok')
	}
}

Promise.resolve方法会将这个对彖转为Promise对象,然后立即执行thenable对象的then方法。返回的promise会“跟随”这个thenable的对象,采用它的最终状态;

let thenable = {
	then: function(resolve, reject){
	  console.log('thenable被执行')
	  resolve('ok')
	}
}
let p = Promise.resolve(thenable)
p.then(res => {
  console.log(res)
})

3.参数不是具有then方法的对象或根本不是对象
如果参数是一个原始值,或者是一个不具有then方法的对象,那么Promise.resolve方法返回一个新的Promise对象,状态为Resolved。

let p = Promise.resolve('ok')
p.then(res => {
	console.log(res)
})

4.不带有任何参数
Promise.resolve方法允许在调用时不带有任何参数,而直接返回一个Resolved状态的Promise对象。

let p = Promise.resolve()
p.then(() => {
	console.log('ok')
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag
Projects
None yet
Development

No branches or pull requests

2 participants