简体   繁体   English

JS async await不等待也不阻塞进程

[英]JS async await does not wait and not blocks the process

I want to acheive something like this: 我想要达到以下目的:

setTimeout(function() {
   console.log("1");
}, 3000);

console.log("2");

And I want 1 to be logged before 2. 我希望1在2之前被记录。

I have tried this: 我已经试过了:

async function a() {
  var v = await setTimeout(function() {
    console.log("1");
  }, 3000);
  console.log("2");
}

a();

And I have tried more things but nothing works. 而且我尝试了更多的事情,但是没有任何效果。 How do I tell JS to WAIT until one thing is done, then go to next thing. 我如何告诉JS等待,直到完成一件事,然后再转到下一件事。 Please, WITHOUT THE USE OF PROMISE! 请不要使用承诺!

Thanks. 谢谢。

There is no way to use await/async without promises. 没有承诺就无法使用await/async The whole functionality is based on promises. 整个功能基于承诺。 Sometimes it may seem like it works without promises, but that's only because some other function is returning a promise. 有时似乎没有承诺就可以工作,但这只是因为其他一些函数正在返回承诺。

The best you can do is create a simple wait function that returns the promise and await it. 最好的办法是创建一个简单的等待函数,该函数返回promise并await它。 For example: 例如:

 wait = (time) => new Promise(resolve => setTimeout(resolve, time)) async function test(){ console.log("one") // Pause await wait(2000) // continue console.log("two") } test() 

There is nothing (that you should be using) in javascript that will suspend the event loop and wait. javascript中没有任何东西(您应该使用)会挂起事件循环并等待。 Part of writing JS is learning to work with this fact. 编写JS的一部分是学习使用这一事实。

Your code doesn't work because setTimeout doesn't return a Promise . 您的代码无效,因为setTimeout不返回Promise Here's a little helper function that actually returns a Promise and achieves what you wanted to do: 这是一个小助手函数,它实际上返回一个Promise并实现您想要做的事情:

const sleep = ms => new Promise(res => setTimeout(res, ms));

Use it like this: 像这样使用它:

async function a() {
  await sleep(3000);
  console.log("1");
  console.log("2");
}

a();

This waits for 3000 milliseconds, logs "1" and then "2" . 这等待3000毫秒,先记录"1" ,然后记录"2" I don't get why you would need to wait before something happens, but I just "translated" your code to actually use Promises. 我不明白为什么您需要等待某些事情发生,但是我只是“翻译”了您的代码以实际使用Promises。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM