如何从nodejs中的JSON检索对象?
拥有此代码:
const fs = require('fs')
const file = 'books.json';
class Book{
constructor(code) {
this._code = code;
}
get code() {
return this._code;
}
set code(value) {
this._code = value;
}
}
async function writeBooks(){
const data = JSON.stringify([new Book('c1'), new Book('c2')]);
await fs.promises.writeFile(file, data, 'utf8');
}
async function getBook(code){
try{
const data = await fs.promises.readFile(file);
const array = JSON.parse(data);
return array.find(b => b.code === code);
} catch (err){
console.log(err)
}
}
writeBooks();
getBook('c1').then(b => console.log(b));
我会得到未定义的
(而不是预期的书籍对象)。
如何获取对象(上述问题)
如果
async
函数始终返回承诺,那么我如何返回客户端的对象,而不是他必须调用then()
then()< /code>来自
getBook(code)
?我是否需要
等待
fs.promises.writefile()
?就像我在writebooks()
中所做的那样?我知道async/等待
现在,从等待
函数的返回值是数据或错误。但是由于writefile()
最多不会返回任何内容,或者最多没有错误(而不是readfile()
),为什么我要等待
对于没有数据?
Having this code:
const fs = require('fs')
const file = 'books.json';
class Book{
constructor(code) {
this._code = code;
}
get code() {
return this._code;
}
set code(value) {
this._code = value;
}
}
async function writeBooks(){
const data = JSON.stringify([new Book('c1'), new Book('c2')]);
await fs.promises.writeFile(file, data, 'utf8');
}
async function getBook(code){
try{
const data = await fs.promises.readFile(file);
const array = JSON.parse(data);
return array.find(b => b.code === code);
} catch (err){
console.log(err)
}
}
writeBooks();
getBook('c1').then(b => console.log(b));
I am getting undefined
(instead of the expecting book object).
How to get the object (the above problem)
If
async
function always returns promise, how can I then return object for the client, instead of him having to callthen()
from thegetBook(code)
?do I need to
await
for thefs.promises.writeFile()
? as I am doing inwriteBooks()
? As fas as I understand theasync/await
now, is that the return value fromawait
function is the data or error. But since thewriteFile()
does not returns anything, or error at most (as opposed toreadFile()
) why would I want toawait
for no data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,问题的根源不是异步/等待或承诺。问题是试图将数组写入JSON文件。如果您像下面的代码段一样编写JSON数据(作为键值对),则解决了您的问题。
Actually the root of problem is not about async/awaits or promises. The problem is trying to write an array to a json file. If you write your json data like the code snippet below (as a key-value pair), your problem is solved.
以上问题是从
json.parse
返回的书籍只有数据,而不是方法,因此我无法通过获得
,但仅作为类的公共参数code
获取代码( ){}book
作为book._code
,但是破坏了封装(对话是_ [propery]
是私人的,应该有适当的getter/setter)。因此,我将属性公开(并破坏了封装),因为我仍然不知道,如何将方法分配给JSON创建的对象。否,
async
的结果始终是保证。您不能在async
中将其解开,客户端将始终必须将其解开。 (因此等待fs.promises.writefile()
将将其解开,但随后立即将其包装回,然后在异步函数返回之前。。
如上所述。
The above problem is that the Books returned from
JSON.parse
have only data, not methods, and thus I cannot get thecode
viaget code(){}
, but only as public parameter of classBook
asbook._code
, which however breaks encapsulation (convetion is that_[propery]
is private, and there should be appropriate getters/setters). So I made the properties public (and broke encapsulation), because I still don't know, how to assign methods to object created from JSON.No, the result of
async
is always Promise. You cannot unwrap it insideasync
, the client will always have to unwrap it. (soawait fs.promises.WriteFile()
will unwrap it, but then immediately wrap it back, before async function returns.as explained above.