0
0

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 3 years have passed since last update.

[メモ][JavaScript] Promise と async await

Posted at

Promiseとは

ES6から使える、非同期処理の最終的な完了もしくは失敗を表すオブジェクト。
従来の非同期処理より可読性が高くなった

(IEはゴミなので使えないのでトランスパイルが必要。)

構文

new Promise(function(resolve, reject){

}).then(

).catch(

).finaliy(

);

resolveが呼ばれると、thenメソッドに行き、rejectが呼ばれるとcatchにいく
finaliyは最後に呼ばれる。

下記の例だと、OKを押すとresolveを実行するので、thenに処理が移る。
1つ目のthenが終わると、2つ目に行く。
そして、最後にfinallyが呼ばれて終わる。

new Promise((resolve, reject) => {
  const yn = confirm("Yes Or No");
  yn ? resolve() : reject();
})
  .then(() => alert("then なう"))
  .then(() => alert("then2 なう"))
  .catch(() => alert("catch なう"))
  .finally(() => alert("おしまい"));

プロミスチェーン

非同期処理を順に実行していくこと

例えば、 下記はチェーンになっているわけではなく、順々に実行していっているだけ

new Promise(function(resolve, reject) {
    resolve(1);
}).then(val => {
  return val * 2;
}).then(val =>{
  return val + 3;
})

プロミスチェーンとは簡単に言うと、thenの中でPromiseを返すこと
そうすると、非同期処理が順に呼ばれていく

function hoge(val = 0) {
  return new Promise(function (resolve, reject) {
    setTimeout(() => {
      alert(val++);
      resolve(val);
    }, 1000);
  });
}

hoge()
  .then((val) => {
    return hoge(val);
  })
  .then((val) => {
    return hoge(val);
  });

並列処理

Promise.allを使う

すべてのプロミスが解決されるか、拒否されるかするまで待ちます。

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values); // 全部のプロミスが終わったあと実行される
});

async await

ES8から導入された、Promiseを書きやすくしたもの

書く必要ないくらい良い記事があった...
https://ja.javascript.info/async-await

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?