2

I am new to JS and was learning async await. So, what I cannot get is that why async function returns promise. Here is the sample code which returns data wrapped inside promise but why inside promise javascript

class Ajax {
    async getPost(url) {
        const header = await fetch(url);
        const data = await header.json();
        return data;
    }
 }
Sai Manoj
  • 3,809
  • 1
  • 14
  • 35
  • 2
    Because a function in JavaScript can't pause. Because future is modeled by promises. Because that's how it's defined. – Amadan Jul 19 '19 at 11:15
  • I personally did not understand your question, could you rephrase maybe please? Maybe console.log the part you don't understand – Quentin C Jul 19 '19 at 11:17
  • 2
    How else would you return `data`? The function is asynchronous, which means that if you call it, it continues to run your code without waiting for that function. If you want to use the return value, you need a way to get it after that function has completed, which is what Promises are used for. – Ivar Jul 19 '19 at 11:21
  • The reason is, that the `await`/`async` syntax was introduced as a way to work with Promises more easily. So the most intuitive and consistent way, out of that perspective, would be that an `async` function just returns a Promise like Promise based APIs did before. – t.niese Jul 19 '19 at 11:28
  • to understand `async/await`, it is helpful to understand the evolution from `callback hell/pyramid of doom` to `promise` and `promise.then()` to `async/await`. the reason async functions return promises is because they were designed that way to complement coding patterns and requirements that arose from everyday JavaScript practise. MDN web docs on promise, using promises and async are helpful in clarifying syntax, whilst articles like this are good for understanding them in context: https://itnext.io/javascripts-async-await-versus-promise-the-great-debate-6308cb2e10b3?gi=9625f245926a – user1063287 Aug 05 '19 at 17:01

0 Answers0