Dmi*_*nko 2 javascript fetch promise
我有以下代码用于处理Magento 2 REST API。
return new Promise((resolve, reject) => {
fetch(uri, { method, headers, body: JSON.stringify(data) })
.then(response => {
return response.json();
})
.then(responseData => {
resolve(responseData);
})
.catch(error => {
reject(error);
});
});
Run Code Online (Sandbox Code Playgroud)
我想添加响应状态检查,所以我已经开始像这样
return new Promise((resolve, reject) => {
fetch(uri, { method, headers, body: JSON.stringify(data) })
.then(response => {
return {
data: response.json(),
ok: response.ok,
status: response.statusText
};
})
.then(responseResult => {
if (responseResult.ok) {
resolve(responseResult.data);
} else {
const error = responseResult.status || responseResult.data.message;
reject(error);
}
})
.catch(error => {
reject(error);
});
});
Run Code Online (Sandbox Code Playgroud)
Magento将错误文本保留在其中data.message
,但response.json()
返回a Promise
而不是data
。
处理这种情况的正确方法是什么?
您将成为显式Promise
创建反模式的牺牲品。您根本不需要new Promise
该代码,只需在then
处理程序中添加状态检查即可:
return fetch(uri, { method, headers, body: JSON.stringify(data) })
.then(response => {
if (!response.ok) {
return response.json()
.catch(() => {
// Couldn't parse the JSON
throw new Error(response.status);
})
.then(({message}) => {
// Got valid JSON with error response, use it
throw new Error(message || response.status);
});
}
// Successful response, parse the JSON and return the data
return response.json();
});
Run Code Online (Sandbox Code Playgroud)
现在:
message
从解析的JSON中使用该错误作为错误(拒绝),response.status
如果没有错误,请重新使用。response.status
用作错误(拒绝) 归档时间: |
|
查看次数: |
880 次 |
最近记录: |