Promise

A promise object is created from Promise constructor/class which needs a callback function AKA executor function . 

This callback function receives the resolve and reject function arguments, either of which we must envoke with an optional payload.

When resolve is called,then method (AKA handler) is called which executes successCallback with successPayload while if reject is called,catch handler is called which executes errorCallback with errorPayload. finally handler is always called (without any payload) when the promise is settled, which means either resolve or reject is called.finally is called before then or catch handler if it appears first i.e, before then or catch handler.

Attention:

1. catch handler will be invoked by the promise not only when we reject the promise but even when JavaScript encounter runtime error in the executor function of the promise.


In the above example, we are trying to increment a variable which does not exist. Since this error was thrown in the executor function, Promise catches it and calls then catch handler with the error payload. If the runtime error occurs in the callback function of an async call (inside the executor function), then the error will won’t be caught, as shown below.


2.  The then handler takes the second argument which should be a function to handle the promise rejection.But it is standard practice to use the catch method handler to handle promise rejection instead of using then method. If you use both catch and then method to handle promise rejection, catch handler will be ignored.

Priority: 宏任务同步-> 微任务(microtask queue, such as Promise) -> 宏任务异步(macrotask queue, such as setTimeOut, setInterval, setImmediate)

From the above example, all synchronous console.log statements got executed first because they were pushed on thestackfirst. Then we had callback of setTimeout waiting on the macrotask queue while the callback of promiseA was waiting on the microtask queue and event loop chosemicrotaskto be executed first and then amacrotask.


Promise.resolve( data ) and Promise.reject( errData )

The resolve and the reject are the static methods of Promise class which returns a promise object and immediately fulfils and rejects it respectively. For example, Promise.resolve() method looks similar to below.

const fulfilledPromise = new Promise( ( resolve ) => resolve() )

But an important thing to remember about promises is that even when we are calling resolve or reject immediately, i.e., without an async function, its callback handlers will be called only when the main JavaScript execution has done all pending work. That means, once the stack is empty, our promise handlers will get executed.


Different states of a promise

As we know that a promise will be fulfilled when resolve is called from within the executor function and then it invokes then handler. Until then, a promise is in the pending state, which means it is yet to be settled. Once resolve is called, it acquires fulfilled state or when reject is called, it acquires rejected state. Promise does not provide any API to check the current state of a promise but you can use debugger tool to convince yourself.


Promise handler returns a new promise

We have seen then, catch and finally methods which are prototype methods of Promise class. These methods are chainable, which means we can call them on each other. This is possible because all these methods return a new promise.

If the promise is fulfilled, then returns a new fulfilled promise with undefined payload (data). If there is a return statement in the handler function, it returns a fulfilled promise with that return value as the payload.

If the promise is rejected, catch returns a new promise with undefined payload (data). If there is a return statement in the handler function, it returns a fulfilled promise with that return value as the payload.

finally returns a new promise with undefined payload (data). If there is a return statement in the handler function, it returns a fulfilled promise with that return value as the payload.

Only first then is invoked when the promise is fulfilled and only first catch is invoked when the promise is rejected. After that, depending on the appearance of then and catch handlers, the handler function will be called. Let’s see an example of this in details.

Promise.all() and Promise.race()

Promise.all([promises]) method takes an array of promises and returns a new promise. This promise will be fulfilled when and if all promises are fulfilled. Promise.race([promises]) also takes an array of promises and returns a new promise which fulfils if any of the promises fulfils.

In the case of both these method, if any of the promises is rejected early, promise returned by these methods will be rejected and the results of other promises will be ignored. In the case of race method, as promises are racing with each other, if one of the given promises fulfils early, returned promise will be fulfilled immediately with the value of the fulfilled promise.

We can also pass non-promise objects inside an array. They will act like a fulfilled promise created using Promise.resolve() function.

Async/Await

Async/Await is a fancier syntax to handle multiple promises in synchronous code fashion. When we put async keyword before a function declaration, it becomes a promise and we can use await keyword inside it which blocks the code until promise it awaits resolves or rejects.

If any of the promises is rejected inside an async function, the promise it returns will reject as well with the error message. The returned promise is also rejected if any runtime error occurs inside the async function (similar behaviour to a promise which rejects when a runtime error occurs in Promise constructors executor function).

The word “async” before a function means one simple thing: a function always returns a promise. If the code has return <non-promise> in it, then JavaScript automatically wraps it into a resolved promise with that value.

The keyword await makes JavaScript wait until that promise settles and returns its result.That doesn’t cost any CPU resources, because the engine can do other jobs meanwhile: execute other scripts, handle events etc.It’s just a more elegant syntax of getting the promise result than promise.then, easier to read and write.

As said, await only works inside async function. Like promise.then, await allows to use thenable objects (those with a callable then method). Again, the idea is that a 3rd-party object may not be a promise, but promise-compatible: if it supports .then, that’s enough to use with await.

For instance, here await accepts new Thenable(1):

If a promise resolves normally, then await promise returns the result. But in case of a rejection, it throws the error, just as if there were a throw statement at that line.

Is async/await blocks the main thread

From await syntax keyword looks like that it blocks the execution of the thread until the promise it is awaiting on resolves. But that’s is not the case. The while async/await pattern is still based on classical Promise syntax.

Async function is more like your promise executor function which runs synchronously. The await keyword is like a then callback that wraps all the statements below it.


refer:

https://itnext.io/javascript-promises-and-async-await-as-fast-as-possible-d7c8c8ff0abc

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,667评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,361评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,700评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,027评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,988评论 5 361
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,230评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,705评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,366评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,496评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,405评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,453评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,126评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,725评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,803评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,015评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,514评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,111评论 2 341

推荐阅读更多精彩内容