等待承诺的 fs.writeFile 与 fs.writeFileSync [英] Await promisified fs.writeFile vs fs.writeFileSync

查看:334
本文介绍了等待承诺的 fs.writeFile 与 fs.writeFileSync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其中一个选项有什么优势吗?

Are there some advantages of one of this options?

1.

const fs = require('fs')

const testFunc1 = async () => {
  fs.writeFileSync('text.txt', 'hello world')
}

2.

const fs = require('fs')
const util = require('util')
const writeFilePromisified = util.promisify(fs.writeFile)

const testFunc2 = async () => {
  await writeFilePromisified('text.txt', 'hello world')
}

我知道 writeFile 和 writeFileSync 之间的区别.问题是返回 testFunc1 和 testFunc2 的承诺之间是否存在一些差异.所以调用是一样的testFunc1.then(...)//或等待 testFunc1或者testFunc2.then(...)//或者等待 testFunc2

I am aware the difference betweeen writeFile and writeFileSync. The question is are there some diffs between promisses that return testFunc1 and testFunc2. So ist it the same to calling testFunc1.then(...) // or await testFunc1 or testFunc2.then(...) // or await testFunc2

当文件写入完成时,这两个承诺将被完成.

These both promisses will be fullfilled when file writing is done.

推荐答案

fs 已经包含 promisify的noreferrer">promisified API.

fs already contains promisified API that doesn't need promisify.

基于承诺的异步版本需要将其用作基于承诺的控制流的一部分,而同步版本不强加此要求.

Asynchronous promise-based version requires to use it as a part of promise-based control flow, while synchronous version doesn't impose this requirement.

异步 ​​readFile/writeFile 是非阻塞的,而同步 readFileSync/writeFileSync 是阻塞的,但允许更快地完成工作.这在密集的 IO 操作期间可能会很明显.

Asynchronous readFile/writeFile is non-blocking, while synchronous readFileSync/writeFileSync is blocking but allows to complete a job faster. This may be noticeable during intensive IO operations.

这篇关于等待承诺的 fs.writeFile 与 fs.writeFileSync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆