惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V2EX - 技术
V2EX - 技术
P
Privacy International News Feed
Security Latest
Security Latest
H
Hacker News: Front Page
T
Tenable Blog
The Hacker News
The Hacker News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Security @ Cisco Blogs
Project Zero
Project Zero
O
OpenAI News
AI
AI
Spread Privacy
Spread Privacy
C
CERT Recently Published Vulnerability Notes
The Last Watchdog
The Last Watchdog
G
GRAHAM CLULEY
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Scott Helme
Scott Helme
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
CXSECURITY Database RSS Feed - CXSecurity.com
NISL@THU
NISL@THU
A
Arctic Wolf
T
Threat Research - Cisco Blogs
PCI Perspectives
PCI Perspectives
N
News and Events Feed by Topic
C
Cyber Attacks, Cyber Crime and Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
Simon Willison's Weblog
Simon Willison's Weblog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Know Your Adversary
Know Your Adversary
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
L
LINUX DO - 最新话题
U
Unit 42
S
Security Affairs
有赞技术团队
有赞技术团队
WordPress大学
WordPress大学
博客园 - 【当耐特】
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
月光博客
月光博客
Engineering at Meta
Engineering at Meta
腾讯CDC
F
Full Disclosure
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 司徒正美
The Cloudflare Blog

开飞机的老张

AGENTS.md Openspec 使用心得 从树莓派内网穿透到 Cloudflare Pages Openclaw和博客 郊眠寺 采石 译:我为什么使用Map(和WeakMap)处理DOM节点 介绍JavaScript中Symbol 原生JavaScript获取URL参数 字符串首字母大写 用forEach()遍历对象 JavaScript禁用按钮 JavaScript的FormData JavaScript的Blob 用FileReader读取本地文件 JavaScript的Thenable JavaScript的立即调用函数表达式(IIFE) JavaScript的Promise链 用interact.js实现拖拽、缩放、吸附
JavaScript中Promise的reject
kaifeiji.cc · 2023-07-25 · via 开飞机的老张

原文:Reject a Promise in JavaScript

在Promise中出现了错误,可以用reject将其标记为rejected状态。

Promise.reject()函数以最简明的方式,将发生已知错误的Promise标记为rejected。在这之后还应该用.catch()处理错误。

1
2
3
4
5
const p = Promise.reject(new Error('Oops!'));

return p.catch(err => {
err.message;
});

当你使用new创建一个Promise时,其实是调用了Promise的构造器。Promise的构造器只接收一个参数——executor函数,Promise随后会执行executor函数,并传入2个参数:resolve()reject()

1
2
3
4
5
6
function executor(resolve, reject) {
typeof resolve;
typeof reject;
}

new Promise(executor);

在executor函数中,要将Promise标记为rejected,可以调用reject(),并传入Error对象

1
2
3
4
5
6
7
const p = new Promise((resolve, reject) => {
reject(new Error('Oops!'));
});

return p.catch(err => {
err.message;
});

reject非Error值

reject并非只支持Error对象,也可以reject其他任意值。

1
2
3
4
5
const p = Promise.reject(42);

return p.catch(err => {
err;
});

但是,许多库和框架假定Promise总是reject一个错误对象,所以在调用Promise.reject()传入其他值的时候,要特别小心。

async/await是JavaScript中并发的未来趋势。“Mastering Async/Await”教你如何在几个小时内,用async/await构建前后端APP,来看看吧!