[英]using async await and .then together
一起使用async/await
和.then().catch()
是否有任何危害,例如:
async apiCall(params) {
var results = await this.anotherCall()
.then(results => {
//do any results transformations
return results;
})
.catch(error => {
//handle any errors here
});
return results;
}
我總是使用async/await
和.catch()
而不是使用async/await
和try/catch
來緊湊地制作代碼。
async function asyncTask() { throw new Error('network') } async function main() { const result = await asyncTask().catch(error => console.error(error)); console.log('result:', result) } main();
如果你想在錯誤發生時得到一個回退值,你可以忽略錯誤並在.catch()
方法中返回一個值
async function asyncTask() { throw new Error('network') } async function main() { const result = await asyncTask().catch(_ => 'fallback value'); console.log('result:', result) } main();
異步函數可以包含一個 await 表達式,該表達式暫停異步函數的執行並等待傳遞的 Promise 的解析,然后恢復異步函數的執行並返回解析的值。
正如您從下面的示例中看到的,您可以使用兩種方法來處理等待結果和錯誤,關鍵字 await 使 JavaScript 等待,直到該承諾解決並返回其結果(您從已解決的承諾中獲得一種)。因此,沒有任何危害(我不完全理解你在這里所說的傷害是什么)。
function returnpromise(val) { return new Promise((resolve, reject) => { if (val > 5) { resolve("resolved"); // fulfilled } else { reject("rejected"); // rejected } }); } //This is how you handle errors in await async function apicall() { try { console.log(await returnpromise(5)) } catch (error) { console.log(error) } } async function apicall2() { let data = await returnpromise(2).catch((error) => { console.log(error) }) } apicall2(); apicall();
如需進一步參考,請查看- MDN DOCS
如果您使用 Async/await,則不需要鏈接.then()
只需將您resolve()
返回的結果存儲在變量中(示例中的response
),但如果您想處理錯誤,則必須嘗試/捕獲你的代碼:
async function f() {
try {
let response = await fetch('http://no-such-url');
} catch(err) {
alert(err); // TypeError: failed to fetch
}
}
在你的承諾中使用:
throw new Error("oops!");
或者
Promise.reject(new Error("Whoops!"));
不想復活死者,但想指出將await
與then
鏈一起使用意味着以下結果:
const x = await someAsyncFn().then(() => doSomeLogging());
x
的值被分配了.then
的返回值,這對我來說不是很直觀。
我不認為混合使用 async/await + then 是個好主意。 尤其是當你專注於 async func 的 res 時,混合使用會帶來一些風險,悄悄地扭曲你的 res。
例子:
const res = await fetchData().then(()=>{return "something else"}).catch((err)=>{});
console.log(res); // not expected res data but something else
所以,混合使用是危險的,順便說一下,它會損害閱讀代碼。
沒有害處,但它的代碼更多且更難閱讀,您可以這樣做:
async apiCall(params) {
try{
var results = await this.anotherCall()
return results;
} catch(err){
//do something with the error
}
}
雖然我不確定您在這里嘗試做什么,但在 try 塊中返回results
僅意味着 function 在錯誤情況下可能會返回 undefined 。
同樣重要的是要記住異步函數總是返回 promise,所以要使用apiCall
function,你有兩種方法:
// 1- using .then to access the returned value
apiCall().then(results => {
if(results){
//doing something with the results
}
})
// 2- awaiting the function inside another async function
async anotherFunction(){
const results = await apiCall();
if(results){
//doing something with the results
}
}
並使用if(results)
確保您處理的不是 undefined
只是為了添加到這組答案中,我總是使用 await 和 then 來使代碼更具可讀性(aws 示例):
幾年前我發現了這個代碼片段(功能),可能在堆棧的某個地方,我只是不記得在哪里!
async function myFunction(){
var params = ....
// either err will be null and data will have a value or if an exception was caused then data will be null and err will contain the information from the catch.
let [err, result] = await to(route53.changeResourceRecordSets(params).promise())
if(err){
// handle the error
}
// carry on
}
to(promise){ // dunno why I called "to" call it anything you like.
return promise.then((data) => {
return [null, data]
}).catch(err => [err])
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.