Search code examples
javascriptecmascript-6promisees6-promise

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?


Solution

  • .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'));