Menu
CoddyTech

Promise'ler

Coddy'nin Node.js Journey'sinin Node.js Temelleri bölümünün bir parçası. Ders 15 / 24.

Geri çağrımların iç içe olması takip etmeyi zorlaştırır ve her birinin err değerini denetlemeyi hatırlaması gerekir.

node:fs/promises bunun yerine bir promise döndürür: daha sonra gelecek bir sonucu temsil eden bir nesne. .then(fn) sonuçla çalışır, .catch(fn) önceki herhangi bir adım başarısız olursa çalışır ve .finally(fn) her iki durumda da çalışır.

import { readFile } from 'node:fs/promises';

readFile('poem.txt', 'utf8')
    .then((text) => console.log(text.length + ' characters'))
    .catch(() => console.log('No poem today'))
    .finally(() => console.log('Bye'));

.then içinde fırlatılan bir hata .catch bölümüne de ulaşır; böylece tek bir işleyici hem okumayı hem de ayrıştırmayı kapsar. .catch olmadan başarısız olan bir promise programı çökertir.

challenge icon

Görev

Kolay
  • count.js dosyasını, node:fs/promises içinden readFile ve .then kullanarak yeniden yaz.
  • Eksik bir dosyada artık .catch içinden No notes yet yazdırılır.
  • Done, .finally içinden yazdırılarak yine en son gelir.

Önce node count.js, ardından node count.js nothere.json komutunu çalıştır.

Kendin dene

import fs from 'node:fs';

const file = process.argv[2] ?? 'notes.json';

console.log('Reading...');
fs.readFile(file, 'utf8', (err, text) => {
    if (err) {
        console.log(`Cannot read ${file}`);
    } else {
        console.log(`${JSON.parse(text).length} notes`);
    }
    console.log('Done');
});

Node.js Temelleri bölümündeki tüm dersler