Promise主要用于异步计算,将异步操作队列化,按照顺序执行,返回结果
可以在对象之间传递promise
new Promise(
function (resolve, reject) {
//.....操作
resolve('成功') // 返回完成
//reject('失败') // 返回出错
}
).then(
(res) => {console.log(res)}, // 显示成功
(err) => {console.log(err)} // 显示失败
)
resolve(): 将Promise的状态从“pending”变为“resolved”,在异步操作成功时调用,并将结果作为参数传递出去
reject(): 将Promise的状态从“pending”变为“rejected”,在异步操作失败时调用,并将错误作为参数传递出去
#简单代码
new Promise(resolve => {
setTimeout(() => {
resolve('hello')
}, 2000)
}).then(res => {
console.log(res)
})
new Promise(resolve => {
setTimeout(() => {
resolve('hello')
}, 2000)
}).then(val => {
console.log(val) // 参数val = 'hello'
return new Promise(resolve => {
setTimeout(() => {
resolve('world')
}, 2000)
})
}).then(val => {
console.log(val) // 参数val = 'world'
})
let pro = new Promise(resolve => {
setTimeout(() => {
resolve('hello world')
}, 2000)
})
setTimeout(() => {
pro.then(value => {
console.log(value) // hello world
})
}, 2000)