resolve()可直接返回Promise成功对象
把一个普通对象转为Promise对象
手动实现Promise对象
// 转成Promise对象
function foo() {
const obj = { name: “why” }
return new Promise((resolve) => {
resolve(obj)
})
}
foo().then(res => {
console.log(“res:”, res) //res: { name: ‘why’ }
})
resolve()实现
// 类方法Promise.resolve
// 普通的值
const promise = Promise.resolve({ name: “swh” })
// 相当于
// const promise2 = new Promise((resolve, reject) => {
// resolve({ name: “swh” })
// })
promise.then(res => {
console.log(“res:”, res) //res: { name: ‘why’ }
})
传入Promise
// 传入Promise
const promise = Promise.resolve(new Promise((resolve, reject) => {
resolve(“11111”)
}))
promise.then(res => {
console.log(“res:”, res) //res: 11111
})
传入thenable对象
// 传入thenable对象
const promise = Promise.resolve({
then: function(resolve, reject) {
resolve(222222)
}
})
promise.then(res => {
console.log(“res:”, res) //res: 222222
})
————————————————
版权声明:本文为CSDN博主「次顶级」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42681555/article/details/121976711