关于Promise知识点

Promise

  • try 捕获错误,catch 查看处理错误
  • throw 自己创建并抛出错误,会阻塞下面代码

什么是 Promise
Promise是一个构造函数,用来封装一个异步操作并可以获取其结果
Promise状态

  • 默认状态:pending, 成功后 pending 变为 resolved
  • 失败后 pending 变为 rejected
    无论变为成功还是失败,都会有一个结果
    Promise 的状态只能改变一次

代码如下(示例):

					 //成功    失败
new Promise(function(resolve,reject){// Promise 属于同步
  }).then(function(){
})

// 举例:
setTimeout(function () {
 console.log(1);
}, 0);
new Promise(function (resolve, reject) {
  resolve("成功返回参数");
  console.log(2);
}).then(function (res) {
   console.log(res); // 输出:成功返回参数, 这里的参数是 resolve 返回的结果
   console.log(3);
});
 console.log(4);
// 结果: 2 4 3 1

- Promise 语法糖

代码如下:

let a = Promise.resolve("成功");
let b = Promise.reject("失败");
 a.then((res) => console.log(res));
 b.catch((err) => console.log(err));

- Promise All

同时执行多个 Promise,所以 Promise 执行成功才算成功,有一个失败就算失败
成功后返回一个 [] 结果的顺序是按照你执行的顺序

let a = Promise.resolve("1:成功");
let b = Promise.reject("2:失败");
let c = Promise.resolve("3:成功");
Promise.all([a, c]).then((res) => {
 console.log(res); // ["1:成功", "3:成功"]
}).catch((err) => {
 console.log(err);
});

- Promise race

谁快就执行谁

let a = Promise.resolve("1:成功");
let b = Promise.reject("2:失败");
let c = Promise.resolve("3:成功");
let aa = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("aa成功");
  }, 0);
 });
Promise.race([aa, a, b, c]).then((res) => {
  console.log(res); // 因为 aa Promise 加了定时器所以执行慢了,就返回那个快的 (结果:1:成功)
}).catch((err) => {
  console.log(err);
});

- Promise.then.then

下面这个 .then(res2) 的结果由上一个 .then执行完返回的值来决定,默认返回 undefined

new Promise((resolve, reject) => {
   resolve("成功");
 }).then((res1) => {
     console.log(res1);
 }).then((res2) => {
  console.log(res2); // undefined
});


new Promise((resolve, reject) => {
  resolve("成功");
}).then((res1) => {
    console.log(res1);
    return "我来决定then的返回值";
}).then((res2) => {
  console.log(res2); // 我来决定then的返回值
});

try

console.log(a); // Uncaught ReferenceError: a is not defined at
// 因为上面代码报错,下面代码都不会执行, 但如何报错之后依然执行呢 ?
console.log("我要执行啊-----");
 //这样即使报错也不会阻止下面代码运行,也可以
try {
 console.log(a);
} catch (err) {
 console.log(err);
}
console.log("我执行了1-----");
console.log("我执行了2-----");
console.log("我执行了3-----");

throw

throw new Error("不能执行下面代码");// Uncaught Error: 不能执行下面代码 at
console.log(1);

async await

一个函数如果加上 async , 那么该函数就会返回一个 Promise

console.log(1);
async function f() {
// async 返回值是一个 Promise 对象,await只能得到成功的结果
// 必须等到 await 后面的代码执行完,才能执行下面的
  await console.log(3);
  console.log(2); // await 下面的所有代码都变成了异步
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值