我是否错误地使用了promise.all()?

oxcyiej7  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(405)

代码在这里
我试图循环返回响应的迭代,以便根据需要准确地描述信息。
当前,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)
    });   
    };

你可以看到,一旦这里出现了未定义的联系人,但是之后正确显示了,我可能会在这里感到困惑,试图使用错误的方法来实现我需要的结果。
控制台日志显示:

{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"]

plicqrtu

plicqrtu1#

是的,你所做的毫无意义。

const caseContactName = Promise.resolve(response.data[i].Contact.name);
const caseSiteName = Promise.resolve(response.data[i].Site.siteName);

Promise.all([caseContactName,caseSiteName]).then((values) => {
  callRmaInvent(caseContactName, caseSiteName)  
});

在这个代码示例中,您向 Promise.all() . then处理程序将获得这两个承诺的结果,但您不会将结果传递给 callRmaInvent ,你通过了最初的承诺。
因此,您需要这样做:

const caseContactName = Promise.resolve(response.data[i].Contact.name);
const caseSiteName = Promise.resolve(response.data[i].Site.siteName);

Promise.all([caseContactName,caseSiteName]).then((values) => {
  callRmaInvent(values[0], values[1])  
});

然而,使用 Promise.resolve() 此处不需要,因为您已经有了数据,因此可以进一步缩短为:

const caseContactName = response.data[i].Contact.name;
const caseSiteName = response.data[i].Site.siteName;

callRmaInvent(caseContactName, caseSiteName)

整个外部方法可简化为:

const callRmaCases = async () => {

  //    $tbody.empty(); 
  const response = await axios.get('/api/Case');
  for(const item of response.data) {
     const caseContactName = item.Contact.name;
     const caseSiteName = item.Site.siteName;

     callRmaInvent(caseContactName, caseSiteName);
  }
}
cgh8pdjw

cgh8pdjw2#

我想你把一切都杀光了。我已经重写了一个更简单的代码版本。可能需要根据服务器的响应进行一些更改。

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])
}   
};

未解决的承诺可以通过多种方式处理。我喜欢异步等待。

相关问题