我是否错误地使用了 Promise.all()?
2021-07-26
77
代码在此
我试图循环遍历返回响应的迭代,以根据需要准确描述信息。
目前,CaseContactName 和 CaseSiteName 来自不同的 API 调用,然后将数据附加到图表上,但在当前状态下,响应未与与表数据相关的内容同步,因为所有这些值都通过模型关系绑定。
我希望联系人姓名和站点名称能够正确附加,我尝试了 3 种不同的循环方法,它要么附加名字/联系人,要么根本不附加。这是令人恼火的数据,有人建议我使用 Promise.All 函数,因为它用于令人恼火的情况,但我感觉我在这里迷失了方向。
代码如下
const callRmaCases = async () => {
// $tbody.empty();
axios.get('/api/Case').then((response) => {
for(let i = 0; response.data.length > 0; i++){
const caseContactName = Promise.resolve(response.data[i].Contact.name);
const caseSiteName = Promise.resolve(response.data[i].Site.siteName);
console.log(response);
console.log(caseContactName, caseSiteName)
Promise.all([caseContactName,caseSiteName]).then((values) => {
console.log(values);
callRmaInvent([caseContactName,caseSiteName])
});
};
}).catch((err) => {
console.log(err);
})
};
const callRmaInvent = async (caseContactName, caseSiteName) => {
await(caseSiteName, caseContactName);
axios.get('/api/caseDetail').then((items) => {
$tbody.empty();
console.log(items);
console.log('inventory will go here');
items.data.forEach((item) => {
const id = item.id;
// Table data
const caseName = item.Case.caseName;
const caseSite = caseSiteName;
const caseContact = caseContactName;
const itemType = item.Part.partType;
const serialNumber = item.Part.serialNumber;
const createdAt = item.createdAt;
const updatedAt = item.updatedAt;
const faultReason = item.Fault.reasonForReturn;
const dispositionAction = item.Disposition.actionTaken;
const addedToInvent = dateFns.format(createdAt, 'MMM D, YY')
const updatedInvent = dateFns.format(updatedAt, 'MMM D, YY')
$tbody.append(`
<tr>
<td>${id}</td>
<td>${caseName}</td>
<td>${caseSite}</td>
<td>${caseContact}</td>
<td>${serialNumber}</td>
<td>${itemType}</td>
<td>${faultReason}</td>
<td>${dispositionAction}</td>
<td>${addedToInvent}</td>
<td>${updatedInvent}</td>
</tr>`)
});
}).catch((err) => {
console.log(err)
});
};
你可以看到,Contact在这里出现过一次未定义的情况,但是之后就正确显示了,我可能在这里真的很困惑,并试图使用错误的方法来获得我需要的结果。
控制台日志显示:
{data: Array(2), status: 200, statusText: "OK", headers: {…}, config: {…}, …}config: {url: "/api/Case", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}data: (2) [{…}, {…}]headers: {content-length: "1474", content-type: "application/json; charset=utf-8", date: "Mon, 26 Jul 2021 19:47:17 GMT", etag: "W/\"5c2-BNGcGEUTd4sqd6BxFY9mWpUJgeU\"", x-powered-by: "Express"}request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}status: 200statusText: "OK"__proto__: Object
script.js:16 Promise {<fulfilled>: "Blake Thompson"}__proto__: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: "Blake Thompson" Promise {<fulfilled>: "Disney World"}
script.js:15 {data: Array(2), status: 200, statusText: "OK", headers: {…}, config: {…}, …}config: {url: "/api/Case", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}data: (2) [{…}, {…}]headers: {content-length: "1474", content-type: "application/json; charset=utf-8", date: "Mon, 26 Jul 2021 19:47:17 GMT", etag: "W/\"5c2-BNGcGEUTd4sqd6BxFY9mWpUJgeU\"", x-powered-by: "Express"}request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}status: 200statusText: "OK"__proto__: Object
script.js:16 Promise {<fulfilled>: "Eric"}__proto__: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: "Eric" Promise {<fulfilled>: "Warehouse"}
script.js:34 TypeError: Cannot read property 'Contact' of undefined
at script.js:13
script.js:19 (2) ["Blake Thompson", "Disney World"]0: "Blake Thompson"1: "Disney World"length: 2__proto__: Array(0)
script.js:19 (2) ["Eric", "Warehouse"]
2个回答
是的,您所做的没有任何意义。
099346717
在此代码示例中,您将2张承诺将其传递给
Promise.all()
。当时的处理程序将获得这两个承诺的
结果
,但是您不会将结果传递给
callrmainvent
,您通过了原始承诺。
因此,您需要以下内容:
788178879
但是,这里不需要
Promise.resolve()
数据,因此可以进一步缩短为:
932763207
可以简化整个外部方法:
6044449723
Evert
2021-07-26
我想你把一切都搞得太过了。我重写了你的代码的一个更简单的版本。可能需要根据服务器的响应进行一些更改。
const callRmaCases = async () => {
try {
const response = await axios.get('/api/Case')
// assuming you are getting a json object
const responseData = await response.json()
responseData.forEach(innerObject => {
callRmaInvent(innerObject.Contact.name, innerObject.Site.siteName)
})
} catch(error) {
console.table(error.name, error.type, error.stack)
}
};
const callRmaInvent = async (caseContactName, caseSiteName) => {
try {
const items = await axios.get('/api/caseDetail')
$tbody.empty();
items.data.forEach((item) => {
$tbody.append(`
<tr>
<td>${item.id}</td>
<td>${item.Case.caseName}</td>
<td>${caseSiteName}</td>
<td>${item.Part.partType}</td>
<td>${item.Part.serialNumber}</td>
<td>${item.Part.partType}</td>
<td>${item.Fault.reasonForReturn}</td>
<td>${item.Disposition.actionTaken}</td>
<td>${dateFns.format(createdAt, 'MMM D, YY')}</td>
<td>${dateFns.format(updatedAt, 'MMM D, YY')}</td>
</tr>`)
});
} catch(error) {
console.table([error.name, error.type, error.stack])
}
};
未解决的承诺可以通过多种方式处理。我喜欢 async-await。
Ritwik Math
2021-07-26