3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

「async」が「スコープ内でawaitを記述できる関数につけるやつ」じゃなかった

Posted at

:writing_hand: async function

//「async function式」or「async function宣言」で
//「AsyncFunction」オブジェクトを返すasync関数を定義
let f = async function(x) {
  return x;
};

console.log(f);
// -> [AsyncFunction: f]

console.log(async function f(x) {
  return x;
});
// -> [AsyncFunction: f]
AsyncFunctionオブジェクトについて
// AsyncFunctionはグローバルオブジェクトではないのでこんな感じで取得して使える
const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor;
let f = new AsyncFunction("x", "return x;");

console.log(f);
// -> [AsyncFunction: anonymous]
async関数(AsyncFunctionオブジェクト)が呼び出された場合はPromiseを返す
let f = async function(x) {
  return x;
};
console.log(f());
// -> Promise { undefined }

async 関数が呼び出された場合、 Promise を返します。

... 🤦

つまり
// Promiseなのでreturn, errorでthen, catchに繋げられる
let f = async function(x) {
  if (x === "🙋") {
    return x;
  } else {
    throw new Error("🚨");
  }
};

f("🙋")
  .then(v => console.log(v))
  .catch(e => e);
// -> 🙋

f("🙆")
  .then(v => v)
  .catch(e => console.log(e.message));
// -> 🚨

:moyai: 「...ずっと無駄なPromiseでラップしてましたわ」

JavaScript の async/await の仕様をずっと誤解していた
async function
async function expression
AsyncFunction

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?