如何返回真正有效的可用对象

时间:2018-06-04 00:22:36

标签: javascript ecmascript-6 promise es6-promise

我正在尝试创建一个返回值的thenable对象,但不起作用:

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

test()
  .then(console.log)

然后调用then,但是console.log不是。任何想法为什么?

1 个答案:

答案 0 :(得分:1)

.then应该是一个接受回调作为参数的函数 - 您的then定义没有。

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