Skip to Content
JavaScript 权威指南(原书第7版)
book

JavaScript 权威指南(原书第7版)

by David Flanagan
March 2021
Intermediate to advanced
610 pages
51h 54m
Chinese
China Machine Press
Content preview from JavaScript 权威指南(原书第7版)
326
13
我们通常会传入兑现值,创建一个很快就兑现为该值的期约对象。但是这个方法的名字
并不叫
Promise.fulfill()
。如果把期约
p1
传给
Promise.resolve()
,它会返回一个新
期约
p2
p2
会立即解决,但要等到
p1
兑现或被拒绝时才会兑现或被拒绝。
写一个基于期约的函数,其中值是同步计算得到的,但使用
Promise.resolve()
异步返
回是可能的,但不常见。不过在一个异步函数中包含同步执行的代码,通过
Promise.
resolve()
Promise.reject()
来处理这些同步操作的值倒是相当常见。特别地,如
果在开始异步操作前检测错误条件(如坏参数值),那可以通过返回
Promise.reject()
创建的期约来报告该错误(这种情况下也可以同步抛出一个错误,但这种做法并不推荐,
因为这样一来,函数的调用者为了处理错误既要写同步的
catch
子句,还要使用异步
.catch()
方法)。最后,
Promise.resolve()
有时候也可以用来创建一个期约链的第
一个期约。稍后可以看到几个这样使用它的示例。
从头开始创建期约
对于
getJSON()
getHighScore()
,我们都是一开始先调用一个现有函数得到初始期
约,然后再通过调用该期约的
.then()
方法创建并返回新期约。如果我们不能使用一
个返回期约的函数作为起点,那么怎么写一个返回期约的函数呢?这时候,可以使用
Promise()
构造函数来创建一个新期约对象,而且可以完全控制这个新期约。过程如
下:调用 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript Everywhere

JavaScript Everywhere

Adam D. Scott
重構 JavaScript

重構 JavaScript

Evan Burchard
JavaScript 之美

JavaScript 之美

Anton Kovalyov

Publisher Resources

ISBN: 9787111677222