【发布时间】:2018-05-04 02:40:33
【问题描述】:
我创建了一个 Fetch 函数来使用 JSON API,并为 JSON 对象定义了类型。我对如何定义getCurrentJobAPI 函数的返回类型感到困惑,因为我之后做了一堆.then()。返回值是最后一个 .then() 吗?在我的代码中,最后一个 .then() 是一个 setState,那么它的类型是什么?
getCurrentJobAPI = (): {} => {
const url: string = `dummy_url&job_id=${this.props.currentJob}`;
return fetch(url, {credentials: 'include'})
.then((response) => {
return response.json();
})
.then((json: CurrentJob) => {
console.log(json);
const location = json.inventoryJob.location;
const ref_note = json.inventoryJob.note;
const id = json.inventoryJob.id;
const models = json.inventoryJobDetails.map((j) => {
return Object.assign({}, {
code: j.code,
qty: j.qty
})
});
this.setState({ currentCodes: models, location: location, ref_note: ref_note, id: id})
return json
})
.then((json: CurrentJob) => {
const barcodes = json.inventoryJob.history;
if (barcodes.length > 0) {
this.setState({apiBarcodes: barcodes})
}
this.calculateRows();
this.insertApiBarcodes();
this.setState({ initialLoad: true });
})
};
更新:
虽然我知道我应该将Promise<type> 定义为getCurrentJobAPI 的返回值(参见Gilad 的答案和cmets),但我仍然不确定为什么我不能写Promise<CurrentJob> 如果Fetch 解析为 JSON 响应。
[根据loganfsmyth 的建议,我已经压缩了我的 .then() 语句。]
这里是CurrentJob的类型定义:
type Job = {
user_id: number,
status: 'open' | 'closed',
location: 'string',
history: {[number]: string}[],
note: string,
} & CommonCurrentJob;
type JobDetails = {
iaj_id: number,
code: number,
} & CommonCurrentJob;
type CommonCurrentJob = {
id: number,
qty: number,
qty_changed: number,
created_at: string,
updated_at: string
}
【问题讨论】:
-
返回值是整个promise链。从技术上讲,您可以获取
getCurrentJobAPI()的结果并附加更多then和catch类型的东西。那是你问的吗?否则我不知道该说什么。除了 Promise 本身,你不能返回任何东西,否则它将不再是异步的。 -
如果返回值是整个promise链,如何在Flow中定义Promise的类型?这种情况的文档在哪里?
-
你不能。这不是异步的工作方式。如果您尝试在promise 链之后 运行代码,它可能会在promise 结束之前运行before。所以你不能认为它是返回一个值,因为那是同步的
-
抱歉,我才发现我没有理解你的问题。我的坏
-
不是您问题的答案,但几乎不需要
.thens。你可以使用.then来返回另一个promise,或者作为promise 链中的最终处理程序。大多数中间.then处理程序最终都会返回undefined,因此您可以将它们折叠到第一个.then。
标签: javascript flowtype