![](/img/trans.png)
[英]UnhandledPromiseRejectionWarning: Reject an unhandled promise when processing certain cases with the question
[英]Promise reject giving me an UnhandledPromiseRejectionWarning error
有人可以向我解釋為什么我做錯了嗎? 如何正確解決此問題?
我有以下代碼來執行交易:
async function limitOrder(keys, symbol, type, quantity, price, waitResult) {
var client = await loadKeys(keys);
return new Promise((resolve, reject) => {
client.newOrder({
symbol: symbol,
side: type, //BUY OR SELL
type: 'LIMIT',
quantity: quantity,
price: price,
timeInForce: "GTC",
newOrderRespType: 'RESULT'
}).then(async (response) => {
console.log(response);
resolve({order: response, price: response.price, quantity: response.origQty}); //return back the order ID
}
}).catch((err) => {
console.log(err); //print error if any
reject(err);
});
});
}
這是我第一次編寫Promise函數的方式,並且在reject(err)
行中遇到錯誤。 因此,如果訂單正確執行,則resolve()
確實會將訂單返回給調用此訂單的函數。 但是,如果到達catch塊,則會打印錯誤。 但是, reject
行卻給了我這個錯誤:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
我想要做的是返回錯誤並在另一個函數中處理它(稱為此函數)。
在limitOrder
返回的新Promise的執行limitOrder
,有一個promise鏈,其中catch
返回的promise的值。 鏈中沒有任何進一步的承諾,也不能添加任何承諾(在limitOrder
之外看limitOrder
承諾鏈)。
在catch處理程序中引發錯誤時,catch返回的promise將被拒絕,沒有拒絕處理程序,並生成未捕獲的拒絕錯誤。
一種解決方案是使用適當的修改從limitOrder
返回諾言鏈,以確保成功時使用正確的值進行解析:
async function limitOrder(keys, symbol, type, quantity, price, waitResult) {
var client = await loadKeys(keys);
return client.newOrder({
symbol: symbol,
side: type, //BUY OR SELL
type: 'LIMIT',
quantity: quantity,
price: price,
timeInForce: "GTC",
newOrderRespType: 'RESULT'
})
.then((response) => {
console.log(response);
return {order: response, price: response.price, quantity: response.origQty}); //return back the order ID
}
}).catch((err) => {
console.log(err); //print error if any
reject(err);
});
});
}
如果.then
處理程序是完全同步的.then
則不需要將其聲明為async
。 顯然,如果由於將來的修改有必要將tt放回去。
問題出在client.newOrder( ... )
方法上,您可能在其中還有另一個promise,該承諾會在then
方法中引發錯誤,例如:
return new Promise((resolve, reject) => { if ("type" in p) { Promise.resolve(1) .then((r) => { throw new Error('here is your uncatched error'); resolve(r) }) } else { reject(new Error('special fail')) // this is how to handle Errors } })
我剛剛更新了您的代碼,以使用async / await代替了promise和try-catch塊來處理錯誤。 看看這個:
async function limitOrder(keys, symbol, type, quantity, price, waitResult) {
try {
var client = await loadKeys(keys);
let response = await client.newOrder({
symbol: symbol,
side: type,
type: 'LIMIT',
quantity: quantity,
price: price,
timeInForce: "GTC",
newOrderRespType: 'RESULT'
})
console.log(response);
return { order: response, price: response.price, quantity: response.origQty }; //return back the order ID
} catch (err) {
console.log(err);
throw new Error(err.message);
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.