- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我认为到目前为止我采取的一个原则是:
A promise is a thenable object, and so it takes the message
then
, or in other words, some code can invoke thethen
method on this object, which is part of the interface, with a fulfillment handler, which is "the next step to take", and a rejection handler, which is "the next step to take if it didn't work out." It is usually good to return a new promise in the fulfillment handler, so that other code can "chain" on it, which is saying, "I will also tell you the next step of action, and the next step of action if you fail, so call one of them when you are done."
.then(resolve, reject)
.then(fulfillmentHandler, rejectionHandler)
resolve
并调用
resolve(someValue)
.如果
fulfillmentHandler
不只是
resolve
的另一个名称,那么为什么这个 thenable 不同呢?
class Thenable {
constructor(num) {
this.num = num;
}
then(resolve, reject) {
alert(resolve); // function() { native code }
// resolve with this.num*2 after the 1 second
setTimeout(() => resolve(this.num * 2), 1000); // (**)
}
}
new Promise(resolve => resolve(1))
.then(result => {
return new Thenable(result); // (*)
})
.then(alert); // shows 2 after 1000ms
最佳答案
thenable 是包含标识符为 then 的方法的任何对象。
下面是可以写的最简单的thenable。当给 Promise.resolve
调用时,一个 thenable 对象被强制转换为一个待处理的 Promise 对象:
const thenable = {
then() {}, // then does nothing, returns undefined
};
const p = Promise.resolve(thenable);
console.log(p); // Promise { <pending> }
p.then((value) => {
console.log(value); // will never run
}).catch((reason) => {
console.log(reason); // will never run
});
编写 thenable 的目的是让它获得
被迫 promise 在我们的代码中的某个时刻。但是一个永远不会解决的 promise 是没有用的。上面的示例具有与以下类似的结果:
const p = new Promise(() => {}); //executor does nothing, returns undefined
console.log({ p }); // Promise { <pending> }
p.then((value) => {
console.log(value); // will never run
}).catch((reason) => {
console.log(reason); // will never run
});
当将其强制为 promise 时,JavaScript 将 thenable 的 then 方法视为 Promise 构造函数中的执行程序(尽管从我在 Node 中的测试来看,JS 似乎为执行程序在堆栈上推送了一个新任务,而对于 thenable 的 then 它会将一个微任务)。
Promise.prototype.then
.
Promise.prototype.then
是一种内置方法。因此它已经实现了,我们只是调用它,传递一两个回调函数作为参数:
// Let's write some callback functions...
const onFulfilled = (value) => {
// our code
};
const onRejected = (reason) => {
// our code
};
Promise.resolve(5).then(onFulfilled, onRejected); // ... and pass both to a call to then
另一方面,Promise 构造函数的 executor 回调参数不是内置的。我们必须自己实现它:
// Let's write an executor function...
const executor = (resolve, reject) => {
// our asynchronous code with calls to callbacks resolve and/or reject
};
const p = new Promise(executor); // ... and pass it to a Promise constructor
/*
The constructor will create a new pending promise,
call our executor passing the new promise's built-in resolve & reject functions
as first and second parameters, then return the promise.
Whenever the code inside our executor runs (asynchronously if we'd like), it'll have
said promise's resolve & reject methods at its disposal,
in order to communicate that they must respectivelly resolve or reject.
*/
一个有用的thenable
Promise.resolve
将 thenable 强制为 promise :
const usefulThenable = {
// then method written just like an executor, which will run when the thenable is
// coerced into a promise
then(resolve, reject) {
setTimeout(() => {
const grade = Math.floor(Math.random() * 11)
resolve(`You got a ${grade}`)
}, 1000)
},
}
// Promise.resolve coerces the thenable into a promise
let p = Promise.resolve(usefulThenable)
// DO NOT CONFUSE the then() call below with the thenable's then.
// We NEVER call a thenable's then. Also p is not a thenable, anyway. It's a promise.
p.then(() => {
console.log(p) // Promise { 'You got a 9' }
})
console.log(p) // Promise { <pending> }
同样,
await
运营商还
将 thenable 强制为 promise
console.log('global code has control')
const usefulThenable = {
// then() will be enqueued as a microtask when the thenable is coerced
// into a promise
then(resolve, reject) {
console.log("MICROTASK: usefulThenable's then has control")
setTimeout(() => {
console.log('TASK: timeout handler has control')
const grade = Math.floor(Math.random() * 11)
resolve(`You got a ${grade}`)
}, 1000)
},
}
// Immediately Invoked Function Expression
let p = (async () => {
console.log('async function has control')
const result = await usefulThenable //coerces the thenable into a promise
console.log('async function has control again')
console.log(`async function returning '${result}' implicitly wrapped in a Promise.resolve() call`)
return result
})()
console.log('global code has control again')
console.log({ p }) // Promise { <pending> }
p.then(() => {
console.log('MICROTASK:', { p }) // Promise { 'You got a 10' }
})
console.log('global code completed execution')
输出:
/*
global code has control
async function has control
global code has control again
{ p: Promise { <pending> } }
global code completed execution
MICROTASK: usefulThenable's then has control
TASK: timeout handler has control
async function has control again
async function returning 'You got a 10' implicitly wrapped in a Promise.resolve() call
MICROTASK: { p: Promise { 'You got a 10' } }
*/
TL;DR:始终编写 thenable 的 then 方法,就像编写 Promise 构造函数的 executor 参数一样。
关于javascript - 在 JavaScript ES6 中,thenable 的接受如何解决和拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59492809/
问题是标题。我正在尝试更深入地了解 promises,我想我已经弄清楚了 Promise.resolve(thenable) 的工作原理,或者至少大部分是如何工作的,查看 MDN 上的示例。我想知道两
我试图理解 resolve(thenable) 和 resolve('non-thenable-object') 之间的区别。 在下面的示例中,使用 promise 而不是 thenable,因为 p
我正在尝试创建一个返回值但不工作的 thenable 对象: const fetchItem = () => 'item'; function test() { return { asyn
如何在返回 Deferred.promise() 的函数之后运行返回 promise 的函数? 我在 JSFiddle 上有一个问题示例.警报消息旨在以“第三次执行?”结尾。而不是在“首先执行?”中间
我知道 thenable 具有 then 方法,但是 Promise 如何知道 thenable 对象的状态已转为拒绝? 示例:在这里,$.ajax 是一个 thenable,如果你这样做的话,可以将
这个问题已经有答案了: How to return many Promises and wait for them all before doing other stuff (6 个回答) How d
thenable 链接如何异步?看起来从上一个 Promise.then 返回的 promise 正在阻塞(其意图本身就是按照下面给出的示例阻塞)下一个 Promise.then 在链中。我对 Nod
我的项目中有这样的代码: co(function *asyncFn() { let browser = yield someAsyncOperation(); return brows
我有一个函数接受 thenable(具有 then() 方法的对象;参见 MDN JavaScript docs: Promise.resolve() 的顶部)或其他: function resolv
我有一个函数可以返回 firebase firestore 查询的快照。如下: export async function getClientWorkflowsFromFirebase(clientI
我正在使用 faye browser client使用 promises,我有一个函数可以在执行异步操作后创建一个 faye 客户端,如下所示: function fayeClient() { r
我认为到目前为止我采取的一个原则是: A promise is a thenable object, and so it takes the message then, or in other wor
我正在开发一个用 F# 编写的 vscode 扩展,使用 Fable 编译成 javascript。许多 api 返回一个 promise 。解析具有返回类型(例如 Thenable)的 promis
我想知道自定义“thenables”(又名带有 .then() 方法的对象)是否被批准/记录?它们与真正的 Promise 相比如何?我想这很重要,那么您如何实现,所以我想知道是否有包含一些 DO 和
这个安全装置有必要吗? Promise.all([...].map((thenable) => Promise.resolve(thenable))); 是否可以安全地将 thenable 提供给收集
这个问题在这里已经有了答案: Does await await promise-like objects? [duplicate] (2 个答案) Custom thenables: Can I c
根据loopback's official docs ,updateAll方法有3个参数:where、data、callback,其中callback为必填项。 Account.deleteSingl
这个问题在这里已经有了答案: Does await await promise-like objects? [duplicate] (2 个答案) Custom thenables: Can I c
当我尝试验证如下条件时。 var val1 = "ONE"; var val2 = "TWO"; expect(val1==val2).to.eventually.equal(false) 我得
根据 MDN: ...if the value is a thenable (i.e. has a "then" method), the returned promise will "follow"
我是一名优秀的程序员,十分优秀!