简体   繁体   English

可以等待/异步在javascript中阻塞非阻塞进程

[英]can await/async makes blocking to non-blocking process in javascript

I read this article from node我从节点阅读了这篇文章

https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/ https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/

It says the code below is a process blocker:它说下面的代码是一个进程拦截器:

const fs = require('fs');
const data = fs.readFileSync('/file.md'); // blocks here until file is read
console.log(data);
// moreWork(); will run after console.log

what if I add await?如果我添加等待怎么办? will the code above becomes non-blocking or it will stay in its true nature?上面的代码会变成非阻塞还是会保持其真实性质?

Example code:示例代码:

const fs = require('fs');
const data = await fs.readFileSync('/file.md'); // no more blocking
console.log(data);

Thank you谢谢

No, the code can't run since await must use in async function .不,代码无法运行,因为 await 必须在async 函数中使用。

And await should use for function that return promise.并且 await 应该用于返回承诺的函数。

the code means:代码的意思是:

// await new Promise(...)
// console.log(...)

new Promise().then((...) => console.log(...))

If you should non-block function, you should use fs.readFile instead.如果你应该使用fs.readFile函数,你应该使用fs.readFile代替。

Blocking means that the whole application is blocked.阻塞意味着整个应用程序被阻塞。

So, all SetInterval , Promise , Events or whatever async callback are paused until that sync function ends its execution.因此,所有SetIntervalPromiseEvents或任何async callback都将暂停,直到该同步函数结束其执行。

It's the same of what you get when you use a for..loop .这与使用for..loop时得到的结果相同。

NodeJS provides you some non-blocking file system methods with callbacks, just change your code like this. NodeJS 为您提供了一些带有回调的非阻塞file system方法,只需像这样更改您的代码即可。

const fs = require('fs');
fs.readFile('/file.md', (err, data) => {
    if (err) throw err;
    console.log(data)
});

There is the only way.这是唯一的方法。

await operator wait a promise, and wrapped in async function await 操作符等待一个承诺,并包裹在 async 函数中

you should code like this你应该这样编码

const fs = require("fs");

function readFile(fileName) {
  return new Promise((resolve, reject) => {
    fs.readFile(fileName, (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
}

async function f1() {
  try {
    var x = await readFile("foo.json");
    console.log(x);
  } catch (e) {
    console.log(e); // 30
  }
}

f1();

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

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