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

推荐订阅源

L
Lohrmann on Cybersecurity
Martin Fowler
Martin Fowler
Engineering at Meta
Engineering at Meta
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
TaoSecurity Blog
TaoSecurity Blog
博客园_首页
Vercel News
Vercel News
Hugging Face - Blog
Hugging Face - Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Last Week in AI
Last Week in AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
The Exploit Database - CXSecurity.com
量子位
Project Zero
Project Zero
A
Arctic Wolf
小众软件
小众软件
NISL@THU
NISL@THU
C
CERT Recently Published Vulnerability Notes
有赞技术团队
有赞技术团队
MongoDB | Blog
MongoDB | Blog
博客园 - 聂微东
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
宝玉的分享
宝玉的分享
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
P
Privacy & Cybersecurity Law Blog
Security Latest
Security Latest
B
Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
D
DataBreaches.Net
Schneier on Security
Schneier on Security
The Hacker News
The Hacker News
K
Kaspersky official blog
C
Check Point Blog
Hacker News: Ask HN
Hacker News: Ask HN
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Webroot Blog
Webroot Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
人人都是产品经理
人人都是产品经理
AI
AI
Cisco Talos Blog
Cisco Talos Blog
MyScale Blog
MyScale Blog
Cloudbric
Cloudbric
B
Blog RSS Feed
S
Schneier on Security
P
Palo Alto Networks Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
'return await promise' vs 'return promise' in JavaScript
Dmitri Pavlutin · 2021-08-10 · via Dmitri Pavlutin Blog
Post cover

When returning from a promise from an asynchronous function, you can wait for that promise to resolve return await promise, or you can return it directly return promise:


async function func1() {

const promise = asyncOperation();

return await promise;

}

// vs

async function func2() {

const promise = asyncOperation();

return promise;

}


You'll see shortly that both expressions do work.

However, are there cases when these expressions behave differently? Let's find out!

1. Same behavior

To find the difference between the 2 expressions (return await promise vs return promise), I'm going to use a helper function delayedDivide(n1, n2).

The function divides 2 numbers, and returns the division result wrapped in a promise:


function promisedDivision(n1, n2) {

if (n2 === 0) {

return Promise.reject(new Error('Cannot divide by 0'));

} else {

return Promise.resolve(n1 / n2);

}

}


If the second (divisor) argument is 0, the function returns a rejected promise because division by 0 is not possible.

Ok, having the helper function defined, let's divide some numbers.

The following function divideWithAwait() uses return await promisedDivision(6, 2) expression to return the division of 6 by 2 wrapped in a promise:


async function divideWithAwait() {

return await promisedDivision(6, 2);

}

async function run() {

const result = await divideWithAwait();

console.log(result); // logs 3

}

run();


Open the demo.

Inside the run() function the await divideWithAwait() expression evaluates to the division result 3. All good.

Now let's try to use the second expression without the await keyword, and return directly the promise wrapping the division result return promisedDivision(6, 2):


async function divideWithoutAwait() {

return promisedDivision(6, 2);

}

async function run() {

const result = await divideWithoutAwait();

console.log(result); // logs 3

}

run();


Open the demo.

Even without using the await keyword inside divideWithoutAwait(), the expression await divideWithoutAwait() inside the run() function still evaluates correctly to the 6 / 2 division as 3!

At this step, you have seen that using return await promise and return promise don't differ. At least when dealing with successfully fulfilled promises.

But let's search more!

2. Different behavior

Now let's take another approach, particularly try to work with rejected promises. To make the function promisedDivision(n1, n2) return a rejected promise let's set the second argument to 0.

Because promisedDivision(n1, 0) now would return rejected promises, let's also wrap the invocation into a try {... } catch (error) {...} — to see whether the rejected promise is caught.

Ok, let's use return await promisedDivision(5, 0) expression with the await keyword:


async function divideWithAwait() {

try {

return await promisedDivision(5, 0);

} catch (error) {

// Rejection caught

console.log(error); // logs Error('Cannot divide by 0')

}

}

async function run() {

const result = await divideWithAwait();

}

run();


Open the demo.

Because the division by zero is not possible, promisedDivision(5, 0) returns a rejected promise. The catch(error) { ... } successfully catches the rejected promise thrown by promisedDivision(5, 0).

What about the second approach, where the await is omitted?


async function divideWithoutAwait() {

try {

return promisedDivision(5, 0);

} catch (error) {

// Rejection NOT caught

console.log(error);

}

}

async function run() {

const result = await divideWithoutAwait();

}

run(); // Uncaught Error: Cannot divide by 0


Open the demo.

This time, however, catch(error) { ... } doesn't catch the rejected promise.

Now you can easily see the main difference between using return await promise and return promise:

When being wrapped into try { ... }, the nearby catch(error) { ... } catches the rejected promise only if the promise is awaited (which is true for return await promise).

3. Conclusion

In most situations, especially if the promises successfully resolve, there isn't a big difference between using return await promise and return promise.

However, if you want to catch the rejected promise you're returning from an asynchronous function, then you should definitely use return await promise expression and add deliberately the await.

catch(error) {...} statement catches only awaited rejected promises in try {...} statement.

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developing a gift boxes Shopify app, and blogging about Shopify. Living in the sunny Barcelona. 🇪🇸