Thenables in JavaScript phục vụ cho bài viết trên (ok)
Thenables in JavaScript
Apr 17, 2020
In JavaScript, a thenable is an object that has a then()
function. All promises are thenables, but not all thenables are promises.
Many promise patterns, like chaining and async/await, work with any thenable. For example, you can use thenables in a promise chain:
You can also use thenables with await
:
Thenables in the Wild
Many libraries implement thenables to enable async/await support. For example, Mongoose queries are thenables, although they also have an exec()
function that returns a promise. Superagent is a popular HTTP client that also uses thenables. However, neither Mongoose queries nor Superagent requests are actually promises.
Other libraries use promises directly. For example, Axios requests are promises in the sense that they are instanceof Promise
.
You can convert an arbitrary thenable to a promise using Promise.resolve()
:
Async/await is the future of concurrency in JavaScript. "Mastering Async/Await" teaches you how to build frontend and backend apps using async/await in just a few hours. Get your copy!
Last updated