【问题标题】:Flow does keeps interpreting variables as Promises after async/awaitFlow 确实在 async/await 之后将变量解释为 Promises
【发布时间】:2018-12-15 07:00:51
【问题描述】:

复制:

// @flow
type A = { key: string, value: string};

const a:A = {
  key: 'a',
  value: 'a'
};

const foo = ():Promise<A> => {
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            resolve(a);
        }, 1000);
    });
}

const bar = async ():A => {
    const res:A = ((await foo()):any);
    return res;
}

bar();

Try it on flow.org/try

上下文:

当调用一个名为 'foo' 的函数返回一个带有 await 的 Promise 时,变量的类型仍然是 Promise。

如果我们只返回变量,Flow 会正确解释该值,但如果我们键入名为“bar”的函数的返回值,则会触发错误。

19:         return res;
                   ^ Cannot return `res` because property `key` is missing in `Promise` [1] but exists in `A` [2].
References:
[LIB] static/v0.75.0/flowlib/core.js:583: declare class Promise<+R> {
                                                        ^ [1]
17:     const bar = async ():A => {
                             ^ [2]

已尝试的解决方案:

  • 强制类型为调用 await 的变量的“A”
  • 使用任何“A”进行强制转换似乎无法解决错误。

相关问题:

https://github.com/facebook/flow/issues/5294

本题目的:

我主要是在寻找解决方法

【问题讨论】:

  • 在堆栈溢出时,必须将理解您的问题所需的代码直接粘贴到问题中并进行适当的格式化。不允许对代码的唯一引用是外部链接。这是因为外部链接有改变或消失的习惯,因此使问题无法作为长期参考(这是 stackoverflow 的任务之一)。
  • async 函数总是返回一个承诺。要从该承诺中获取价值,请使用 .then()await

标签: async-await es6-promise flowtype


【解决方案1】:

这似乎是一个简单的误解,但Flow的错误消息并不是很有用。

您已将bar 声明为

const bar = async (): A => {

但异步函数总是返回承诺,所以它应该是

const bar = async (): Promise<A> => {

你可以看到here on flow.org/try

【讨论】:

  • 确实,我自己没有找到这个感觉有点愚蠢,但这是正确的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 2020-09-24
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 2021-12-15
相关资源
最近更新 更多