await etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
await etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

16 Mayıs 2020 Cumartesi

await function Anahtar Kelimesi

Giriş
async metodun bitmesini bekler.
Örnek
Elimizde şöyle bir soru olsun
You have three functions, which are all asynchronous:

loadReport(id) which fetches the definition of a report
runReport(report) which runs the report and returns a path to a PDF output file
sendReport(filePath) which mails the file to subscribers and returns true if succeeded

Write code that executes a report using these three functions and shows alert if everything went well. Each of these functions can throw an exception. How would you handle it?
Şöyle yaparız
try {
  const report = await loadReport(id)
  const outputPath = await runReport(report)
  const completed = await sendReport(outputPath)
  alert(completed ? 'Done!' : 'Bad monkey!')
} catch (error) {
  alert(error.message)
}
Örnek
Şöyle yaparız. Her bir saniye de bir dizideki bir sayıyı döner. Çıktı olarak 5,4,3,2,1 alırız.
const delay = ms => new Promise(res => setTimeout(res, ms));
async function x() {
  const array = [1, 2, 3, 4, 5, 6, 7, 8].slice(0, 5);
  for (const item of array.reverse()) {
    console.log(item);
    await delay(1000);
  }
}

x()
Örnek
Elimizde şöyle bir kod olsun.
const getUserByImportMail = async (mail) => {
  const mailResult = ...
  ...
  return mailResult
}
Şöyle yaparız.
const isSenderValid = async mail => {
  const importMail = await getUserByImportMail({importMail: mail})
  ...
  // some checks
  return importMail
}
await yerine Promise.then kullanılabilir. Şöyle yaparız.
const isSenderValid = mail => {
  return getUserByImportMail({importMail: mail})
  .then(importMail => {
      ...
some checks
      return importMail
  });
}