0

Considering the following 2 functions: one return promise object, one using await. Are they exact behavior the same under the hood?

async function f1 (event) {
  const promise = new Promise(function(resolve, reject) {
    fetch('https://google.com')
      .then(p=>p.status)
    });
  return promise
}

async function f2 (event) {
  const res = await fetch('https://google.com');
  return res.status;
}

I believe I can also call like:

var r1 = await f1(url);
var r2 = await f2(url);

Question here: 1. are the 2 callings correct? 2. f1 and f2 under the hook, are they exact same behaviour and usage?

Xin
  • 33,823
  • 14
  • 84
  • 85

1 Answers1

1

If http.get returns a promise you can simplify the promise example to make it look like the await example. To answer your question simply, they do the same thing with different syntax.

async function f1 (event) {
  return https
    .get(url)
    .then(res => res.statusCode);
}

async function f2 (event) {
  const res = await https.get(url);
  return res.statusCode;
}
ktilcu
  • 3,032
  • 1
  • 17
  • 15