user9861429
user9861429

Reputation:

How to return a thenable object that really works

I'm trying to create a thenable object that returns a value, but isn't working:

const fetchItem = () => 'item';
function test() {
  return {
    async then() {
      const item = await fetchItem()
      return item
    }
  }
}

test()
  .then(console.log)

The then is being called, but the console.log it isn't. Any ideias why?

Upvotes: 1

Views: 821

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370979

.then should be a function that accepts a callback as a parameter - your then definition doesn't have one.

function test() {
  return {
    async then(callback) {
      const item = await '3';
      return callback(item);
    }
  }
}
test()
  .then(console.log)
  .then(() => console.log('done'));

Upvotes: 1

Related Questions