【问题标题】:How to return a promise value using Google Datastore? [duplicate]如何使用 Google Datastore 返回承诺值? [复制]
【发布时间】:2017-11-07 19:16:49
【问题描述】:

我目前正在发现 Google Datastore,它似乎非常有用。

但是(我是 JS 新手)我被一些关于 PromiseAsync/await 的非常简单的东西困住了,我找不到答案(我试过了......)。

这个get 在我的终端中完美运行(相当简单):

datastore.get(datastore.key(['viewing', 'abc123']))
.then((slot) => {
  console.log(slot[0])
})

但我想要的是将此查询包装成 const 并按需返回 slot[0]...

所以我试过了:

const wrap = () => {
  datastore.get(datastore.key(['viewing', 'abc123']))
    .then((slot) => {
      return slot[0]
    })
}

没用。 我尝试在datastore.get 之前添加return,将return 更改为Promise.resolve...但它仍然相同:Promise pending(最佳情况)。

我不谈论使用async/await。 我不能return我的slot[0]...

任何线索,谢谢。

【问题讨论】:

    标签: javascript asynchronous promise return google-cloud-datastore


    【解决方案1】:

    你正在处理的是一个承诺。我一直认为,一旦进入“无极之地”,就无法逃脱。有些人可能认为这是一件坏事,但我认为这很好。

    一旦你运行get,它会在未来的某个时候完成。当它执行时,它会调用then 中的函数并将值传递给它。从这一点开始,您必须在 then 语句中工作。 (以下警告)

    您可以保留对承诺的引用并将其用作值

    const omg = datastore.get(datastore.key(['viewing', 'abc123']))
    

    您只能通过使用.then 函数来获取该值。

    omg.then(console.log)
    

    您可以获取您的值并将其传递给另一个函数,无论是 lambda:

    omg
        .then(slot => slot[0])
        .then(console.log)
    

    或命名函数

    const head = list => list[0];
    omg
        .then(head)
        .then(console.log)
    

    这是使用 Promise 的最佳方式

    如果这太陌生或者您不习惯这种类型的编程(函数式),那么您可以使用命令式 Async/Await。

    const omg = await datastore.get(datastore.key(['viewing', 'abc123']))
    

    它应该符合你的预期,但必须通过 babel 或类似的方式进行编译。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 2017-02-07
      • 2017-02-14
      • 2016-12-31
      • 2016-07-27
      • 2014-05-21
      相关资源
      最近更新 更多