【发布时间】: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();
上下文:
当调用一个名为 '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