小编Roj*_*ojo的帖子

在异步函数内的 for 循环内等待会产生奇怪的结果

有人可以帮我解释为什么它会这样吗?

据我所知,await sleep(1)在这种情况下添加该行不应影响代码流。然而,确实如此。

function sleep(time) {
  return new Promise((r) => setTimeout(r, time));
}

async function test(target) {
    const ids = { a: ['a1', 'a2'], b: ['b3', 'b4'] }[target];
    for (id of ids) {
        console.log('X.', target, id);
        // await sleep(1);
        console.log('Y.', target, id);
    }
}

test('a');
test('b');
Run Code Online (Sandbox Code Playgroud)

前

后

为什么?

谢谢!

javascript for-loop async-await

1
推荐指数
1
解决办法
402
查看次数

Javascript Canvas我不想在椭圆的中间描边

所以我试图在画布上用Javascript绘制面孔,而微笑却在起作用ellipse(x, y, rX, rY, rot, start, end。我关闭了路径(closePath();),并通过笔划命令(stroke();)跟随了路径。绘制椭圆,看起来像一个半圆形。但这也画了一个连接半圆的两端的笔触,我不想。看起来像这样:

var c = document.createElement('canvas');
var ctx = c.getContext('2d');
var w = 500;
var h = 300;

window.onload = function() {
  c.style.backgroundColor = '#aaa';
  c.width = w;
  c.height = h;
  c.tabIndex = '1';
  c.style.outline = 'none';
  c.style.display = 'block';
  c.style.margin = '0 auto';
  c.style.position = 'relative';
  c.style.top = '50px';
  document.body.style.margin = '0';
  document.body.appendChild(c);
}

setInterval(function() {
  ctx.clearRect(0, 0, w, h);

  ctx.beginPath();
  ctx.ellipse(w / 2, h / 2, 30, …
Run Code Online (Sandbox Code Playgroud)

javascript

0
推荐指数
1
解决办法
55
查看次数

标签 统计

javascript ×2

async-await ×1

for-loop ×1