LoginSignup
0
0

More than 1 year has passed since last update.

async await メモ

Last updated at Posted at 2021-08-22

sample

const af = async ()=>{
  setTimeout(()=>{
    console.log("anonymouse func")
  }, 500);
  const ret = await new Promise((resolve)=>{
    console.log("promise function");
    //return 123; // Invalid Code
    resolve(123);
  }).then(r=>{
    console.log(`r:${r}`)
    return r
  });
  console.log("end");
  return ret
}

console.log("before")
const ret = af()
console.log("after")
ret.then(r=>console.log(`r ${r}`));

result

> "before"
> "promise function"
> "after"
> "r:123"
> "end"
> "r 123"
> "anonymouse func"

memo

  • async は非同期呼び出しを可能とする定義
  • await は、Promise.resolveでラップした値を返す
  • new Promise()に渡した関数は、引数のresolveに渡された値をPromiseでラップして返す
  • Promise.then()は、resolveされた値を引数に取り、returnした値をPromiseでラップして返す

参考

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/async_function
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/async_function

0
0
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
0
0