Custom thenables: Can I create my own objects with

2019-05-31 00:35发布

问题:

I'm wondering if custom "thenables" (aka an object with a .then() method) are approved/documented? How do they compare to real Promises? I suppose it matters how you implement then, so I'm wondering if there's documentation with some DOs and DONTs.

This page suggests:

.then may return an arbitrary “thenable” object, and it will be treated the same way as a promise.

Can't find any docs on this.

回答1:

How do thenables compare to real Promises?

In that you don't know whether they are real promises or not. Have a look at Regarding Promises/A+ Specification, what is the difference between the terms "thenable" and "promise"?.

I'm wondering if there's documentation with some DOs and DONTs about how to implement them (as that seems to be what matters)

There's the (pretty simple) Promises/A+ specification that documents how thenables are treated. ES6 promises (and by extension, await) follow this. Basically:

  • your object has a property with the name then whose value is a function
  • the function will get called with two callbacks
  • you can call either of them - asynchronously or not
  • the first call determines what happens to the promise that assimilated your thenable

It's really no magic. You call the first argument when you want to resolve with a value, and you call the second argument when you want to reject. There are no DONTs assuming a proper promise implementation - you can call the callbacks as often as you want, and keep them around as long as you want: the calls should be ignored and the reference should not leak memory.