![](/img/trans.png)
[英]UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined Discord.JS
[英]UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
我的代碼:
export const convertToTickerObject = (data) => {
const keys = [
'id',
'last',
'lowestAsk',
'highestBid',
'percentChange',
'baseVolume',
'quoteVolume',
'isFrozen',
'high24hr',
'low24hr'
];
const object = {};
data.forEach((value, i) => {
if (i === 0) {
object.name = getCurrencyPairId(value);
return; //escape arrow function
}
const key = keys[i];
object[key] = value;
});
return object;
};
錯誤:
UnhandledPromiseRejectionWarning:TypeError:無法讀取未定義 UnhandledPromiseRejectionWarning 的屬性“forEach”:未處理的承諾拒絕。 這個錯誤要么是因為在沒有 catch 塊的情況下拋出了異步函數,要么是因為拒絕了一個沒有用 .catch() 處理過的承諾。 (rejection id: 1) (node:7188) [DEP0018] DeprecationWarning:不推薦使用未處理的承諾拒絕。 將來,未處理的承諾拒絕將使用非零退出代碼終止 Node.js 進程。
我嘗試使用 async/await,但此警告不斷發生。
我該如何解決這個警告? :(
正如錯誤中所說,您傳遞的參數可能未定義或不是對象。 嘗試這個:
const convertToTickerObject = (data) => { if ( typeof data !== 'object' ){ return 'Not object. Parameter type: '+ typeof data; } if( Object.keys(data).length === 0 && data.constructor === Object ){ return 'object empty'; } const keys = [ 'id', 'last', 'lowestAsk', 'highestBid', 'percentChange', 'baseVolume', 'quoteVolume', 'isFrozen', 'high24hr', 'low24hr' ]; const object = {}; data.forEach((value, i) => { if (i === 0) { object.name = getCurrencyPairId(value); return; //escape arrow function } const key = keys[i]; object[key] = value; }); return object; };
這可能會揭示其他地方的錯誤。 無論如何,像我添加的那些檢查一樣會很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.