javascript - 如何返回真正有效的 thenable 对象

标签 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 不是。有什么想法吗?

最佳答案

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

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

关于javascript - 如何返回真正有效的 thenable 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50672142/

相关文章:

node.js - 在 Node.js 上的 Express POST 路由中定义/使用 Promise

javascript - async wait 不同场景的区别

javascript - Bluebird - 混合each() 和all()?

javascript - httpUploadProgress 对于缓冲区数据没有按预期工作?

javascript - React Native 中的 ".eslintrc.js"是什么?

javascript - Angular JS 中 ng-if 表达式中条件单向绑定(bind)的语法

javascript 字符串数组到深度合并对象

javascript - 为什么 ES6 IIFE 和 ES5 IIFE 的执行上下文不同?

javascript - 如果另一个数组具有相同的元素,则连接数组元素

javascript - 组正则表达式缺少最后一场比赛