[英]Why does this await return undefined?
I have the following code:我有以下代码:
const checkBatchStatus = async (batchId: number) => {
let result = await fetchcall("POST", "api/batch/status", { "BatchId": batchId })
.then(result => {
Promise.resolve(true);
})
.catch(err => {
Promise.resolve(false);
});
};
the caller code is the following:调用方代码如下:
async function isBatchRequestCompleted(batchId: number) {
let status = await checkBatchStatus(batchId);
console.log(`status is ${status}`);
status is always undefined.状态总是未定义的。 Not understanding why.
不明白为什么。
If I change the checkBatchStatus to simply return false, then I get status equal to false.如果我将 checkBatchStatus 更改为简单地返回 false,那么我的状态等于 false。
const checkBatchStatus = async (batchId: number) => {
return false;
};
Can a kind soul explain to me what I am seeing?一个善良的灵魂可以向我解释我所看到的吗?
You didn't return a value in the function checkBatchStatus()
.您没有在函数
checkBatchStatus()
返回值。 And calling a Promise.resolve()
in callback function of .then()
is a wrong idea if you want just a Boolean value.如果你只想要一个布尔值
.then()
在Promise.resolve()
的回调函数中调用Promise.resolve()
是一个错误的想法。
const checkBatchStatus = (batchId: number) => {
return fetchcall("POST", "api/batch/status", { "BatchId": batchId })
.then(result => {
return true;
})
.catch(err => {
return false;
});
};
You're mixing both promises and async/await unnecessarily here.您在这里不必要地混合了 promise 和 async/await。 I suggest sticking with one or the other.
我建议坚持其中之一。
async
/ await
: async
/ await
:
const checkBatchStatus = async (batchId: number) => {
try {
await fetchcall("POST", "api/batch/status", { "BatchId": batchId });
return true;
} catch {
return false;
}
};
Or promises:或承诺:
const checkBatchStatus = (batchId: number) => {
return fetchcall("POST", "api/batch/status", { "BatchId": batchId })
.then(result => true)
.catch(err => false);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.