一、构造函数:Promise(回调函数)
- promise对象用于白哦是一个异步操作的最终状态(完成或失败),以及其返回的值
let promise=new Promise(function(resolve,reject){
//状态1
//resolve();
//状态2
reject();
});
//resolve才会调用
promise.then(()=>{
console.log("成功,没有问题")
}).then(()=>{
console.log("成功,可以无限调用then方法")
});
//reject后执行
promise.catch(()=>{
console.log("出现了重大问题");
});
二、使用Promise实现异步操作
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
const posts=[
{title:"Post One",body:"this is post one"},
{title:"Post Two",body:"this is post two"}
];
function getPosts(){
setTimeout(()=>{
let output='';
posts.forEach((post,index)=>{
output+=`<li>${post.title}</li>`;
})
document.body.innerHTML=output;
},1000)
}
// function createPost(post,callback){
// setTimeout(()=>{
// posts.push(post);
// callback();
// },2000);
//
// }
function createPost(post){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
posts.push(post);
// const error=true;
const error=false;
if(!error)
{
resolve();
}
else{
reject("Error:something went wrong ")
}
},2000);
});
}
createPost({title:"Post three",body:"this is post three"}).then(getPosts)
.catch(err=>console.log(err))
</script>
</body>
</html>
Promise.all
const promise1=Promise.resolve("hello");
const promise2=Promise.resolve(20);
const promise3=new Promise((resolve,reject)=>{
setTimeout(resolve ,2000)
})
Promise.all([promise1,promise2,promise3]).then (values=>{
console.log(values);
})