最近我一直在问自己如何使用async / await语法重现then / catch的行为。
使用then / catch,我可以定义一个仅在Promise解析后才执行的回调,然后像这样继续执行。
function test() {
getUsersFromDB().then(users => console.log(users));
console.log('The rest of the code here continues to execute');
[...]
// Promise resolves and logs the users value
}
对我来说,使用异步/等待功能,您可以有2种可能的行为。
1。等待功能并阻止其余的执行
async function test() {
const users = await getUsersFromDB();
// Code in here is not executed until promises returns
console.log(users);
}
2。不要等待返回值,但不要期望您保证在其余代码执行时得到满足
function test() {
const users = getUsersFromDB();
// May log undefined
console.log(users);
}
我可以使用async / await重现第一个用例吗?
答案 0 :(得分:1)
使用then
是最简单的解决方案,但是您可以使用AIIFE:
function test() {
(async () => {
const users = await getUsersFromDB();
console.log(users);
})().catch(console.error);
console.log('The rest of the code here continues to execute');
[...]
// Promise resolves and logs the users value
}
另一个选择只能是async do
expressions。
答案 1 :(得分:0)
因此,您基本上需要拆分代码。一件应以异步/等待语法执行,另一件应照常执行。
首先,我想说的是
function getCenter(shape) {
return {
x:
shape.x +
(shape.width / 2) * Math.cos(shape.rotation) +
(shape.height / 2) * Math.sin(-shape.rotation),
y:
shape.y +
(shape.height / 2) * Math.cos(shape.rotation) +
(shape.width / 2) * Math.sin(shape.rotation)
};
}
function Show({ text, x, y, rotation, width, height }) {
const center = getCenter({
x,
y,
width,
height,
rotation: (rotation / 180) * Math.PI
});
return (
<svg width={window.innerWidth} height={window.innerHeight / 2}>
<text
y={height / 1.3}
fill="#000"
fontSize={50}
alignment-baseline="bottom"
transform={`translate(${x}, ${y}) rotate(${rotation})`}
>
{text}
</text>
{/* Origin Circl */}
<circle cx={center.x} cy={center.y} r={10} fill="red" />
</svg>
);
}
可以解决问题。这可能看起来有点奇怪,因为我们只是稍微增加了一点,这不是我们想要的,但是...
async function test() {
console.log('The rest of the code here continues to execute');
const users = await getUsersFromDB();
// Code in here is not executed until promises returns
console.log(users);
}
关键字停止执行await
函数,但是当async
冻结该函数时,我们有一些代码应继续工作,这意味着我们无法放置代码await
之后,仅在此之前。
据我了解,代码tahat表示为“此处的其余代码继续执行”也可以是异步的,因此产生的示例如下:
await