【发布时间】:2019-11-25 10:18:14
【问题描述】:
我正在编写这个链式承诺。
首先,当一个按钮被点击时,它会检查一个文件 url 是否存在:
如果不是,则拒绝,然后在警报中显示响应状态。
如果是,则通过 webapi 更新数据库,然后更新反应状态。
我面临的问题是,即使我在 validateResponse 函数中拒绝,它仍然会在下一个运行。
我觉得应该直接去catch。
此外,下面调用 webapi 的代码似乎不太好,一个 then 中的 promise 等等。整个代码似乎也不清楚?这是更好的方法吗?
onClick: (event, row) => {
function validateResponse(response) {
if (!response.ok) { // assume it is the reject case.
console.log("file not ready");
return Promise.reject(response.statusText);
} else {
window.open(response.url, '_blank', 'location=yes,height=500,width=600,scrollbars=no,status=yes')
return response;
}
}
fetch(row.fileurl, {
method: 'HEAD'
})
.then(validateResponse)
.then(console.log("== this line not printed, due to rejected."))
.then(row.linked = 1)
.then(
fetch(this.server_url+'/file/linked', { method: 'POST', body: JSON.stringify(row), headers: { 'Content-Type': 'application/json' }, })
.then(res => {
console.log("== it should be rejected!, why printed this line2")
if (res.status==200) {
this.setState({ row });
} else {
row.checked = 0;
throw Error(res.status);
}
})
)
.catch(function (error) {
alert("Sorry, the file is not avaliable yet")
});
}
还有一个问题:
.then(() => row.linked = 1)
.then(() => fetch(this.server_url+'/file/linked', { method: 'POST', body: JSON.stringify(row), headers: { 'Content-Type': 'application/json' }, })
如何将其合二为一?
.then(() => row.linked = 1 && fetch(this.server_url+'/file/linked', { method: 'POST', body: JSON.stringify(row), headers: { 'Content-Type': 'application/json' }, })
这是一种更好/正确的方法吗?
【问题讨论】:
-
.then将函数作为参数,但您将指令放入其中。.then(() => console.log(/*...*/))等 -
将
validateResponse()代码滚动到promise链后,你可以得到更好的优化。 -
在完全同步操作之后,您不需要额外的
.then()。您有两个异步操作,fetch(row.fileurl, ...)和fetch(this.server_url + '/file/linked', ...),因此一切都将简化为两个 then 和一个 catch。
标签: javascript reactjs promise