узел js: почему я не могу писать асинхронно в jason.js, а затем читать его синхронно?

Использовать Выражения привязки данных


Код позади,

protected void Page_Load(object sender, EventArgs e){
  DataBind();
}

-1
задан Yosra 18 January 2019 в 14:19
поделиться

2 ответа

Вы хотите попробовать прочитать файл после того, как он записан. Это означает, что вы должны сделать это в функции обратного вызова из writeFile.

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
    console.log('hey there');
    //here I read synchronously from the note.json file
    var file = fs.readFileSync('./note.json');
    var note = JSON.parse(file);

});
0
ответ дан Nick 18 January 2019 в 14:19
поделиться

Добро пожаловать в Stack Overflow!

Что касается ваших вопросов, то вы неправильно обрабатываете асинхронный код. Ваше чтение должно произойти ПОСЛЕ записи, поэтому вы должны сделать следующее:

const fs = require('fs');

var originalNote = {
   title: 'todo list',
   body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
       console.log('hey there');
       //here I read synchronously from the note.json file
       var file = fs.readFileSync('./note.json');
       var note = JSON.parse(file);
});
0
ответ дан LostJon 18 January 2019 в 14:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: