我目前正在使用 React 開發一個訊息傳遞應用程式。目前,我正在努力確定一種延遲向聊天發布訊息的主要功能的方法。
主要問題是使用 Cloudinary API,對于圖片訊息提交,我需要從 POST 請求中吐出的 url。因此,我還需要將 postMessage 方法延遲到我的照片上傳到 Cloudinary 資料庫之后,并且 'temp' 陣列已經收集了新生成的影像 url。我的問題開始并且很可能以我無法確定在我的 forEach 陳述句完成之前延遲 postMessage 的正確方法而結束。
這是我的 handleSubmit 方法的代碼:
const handleSubmit = async (event) => {
event.preventDefault();
const formElements = event.currentTarget.elements;
const formData = new FormData();
let temp = [];
if (imagesSelected.length > 0) {
imagesSelected.forEach((image) => {
formData.append('file', image);
formData.append('upload_preset', 'sendpics');
instance.post('https://api.cloudinary.com/v1_1/dg7d5il8f/image/upload', formData )
.then((res) => {
temp.push(res.data.url);
})
.catch((err) => {
console.log(err);
});
});
const reqBody = {
text: formElements.text.value,
recipientId: otherUser.id,
conversationId,
sender: conversationId ? null : user,
attachments: temp,
};
postMessage(reqBody);
} else {
const reqBody = {
text: formElements.text.value,
recipientId: otherUser.id,
conversationId,
sender: conversationId ? null : user,
attachments: [],
};
postMessage(reqBody);
}
setText('');
setImagesSelected(() => []);
};
問題仍然存在于第一個 if 陳述句中,因為一旦 forEach 陳述句觸發,postMessage 就會在之后觸發,甚至在 temp 有機會填充新的 url 值之前。如果整個問題本身以任何方式令人費解,我們深表歉意。如果我需要澄清我的問題,請發表評論。感謝您的任何幫助/建議!
uj5u.com熱心網友回復:
我認為您需要使用for-of 回圈等待它們 using-async-await-with-a-foreach-loop
您的案例示例:
for (const image of imagesSelected) {
//...
try {
const resp = await instance.post(
"https://api.cloudinary.com/v1_1/dg7d5il8f/image/upload",
formData
);
temp.push(resp.data.url);
} catch (error) {
console.log(error);
}
}
另一種方法是替換forEach并map添加評論中提到的Promise.allAs E. Shcherbo
uj5u.com熱心網友回復:
Array.forEach(callback)不幸的是,如果每個元素都需要異步運行,則不能使用標準方法,因為以下代碼不會等待回圈完成。
一種合適的方法是Promise為每個陣列元素創建一個并等待它們解決。如果您的元素很少,您可以手動完成,或者如果它們太多或根本沒有硬編碼,您可以使用回圈創建該 Promise-array。
也許像這樣:
let promiseArray = []
imagesSelected.forEach(item => {
let p = new Promise((resolve, reject) => {
// do your asynchronous stuff here
instance.post(...
// when you want the code to be "marked" as finished, run
resolve(optionalReturnData)
// when an error happens
reject(optionalReason)
...
})
promiseArray.append(p)
})
// wait for the promises
Promise.all(imagesSelected).then(returnDataArray => {
// now all promises have resolved and you can continue
...
postMessage(...)
})
有關更多詳細資訊,請參閱mdn 檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468918.html
標籤:javascript 反应 异步等待 承诺
下一篇:如何呼叫異步清理函式?
