0
1

More than 1 year has passed since last update.

javascript Promiseを実際に書いて理解する

Last updated at Posted at 2020-04-16

Promiseを理解する。

javascriptを記述するうえで欠かせないのが、非同期処理です。
非同期処理のためPromiseを理解したいと考えております。
(async・awaitという便利な記述もあるみたいですが、それはまた今度)

Promiseを知らないと

今まではPromiseを使わずに、コールバックを多用してました。

作ったもの

ページを読み込んだときのboxの「height」を表示。
3秒後に「height」が変更。
再度「height」を取得してサイズを表示。

実際の記述

<div id="box" style="width: 100px; height: 200px; background-color: #999; color: #fff;">
    <p class="size"></p>
    <h2 id="success"></h2>
</div>
//変数セット
let size = document.querySelector(".size");
let box = document.querySelector("#box");
let success = document.querySelector('#success')


//p.sizeタグに現在のbox高さを表示する。
size.textContent = box.clientHeight;

//プロミスに成功した場合の文章です(stringとする)
var success_text = "成功です";


//Promiseのインスタンスを作成する。
var promi = new Promise(function(resolve,reject){


    //型のチェック:"string型"でなければrejectが作動する
    if(typeof success_text != "string"){
        reject('文字ではありません');
    }


    //〇秒後にcss変更
    setTimeout(function () {
        var width = parseInt(box.style.height);
        box.style.height = 333 + "px";
        return resolve(success_text);
    }, 3000);
});


//Promiseインスタンスの呼び出し
promi.then(function(value){

    //成功したときのフロー
    //console.log(value);
    success.textContent = value;
    size.textContent = box.clientHeight;


    //失敗(エラー)したときはエラー文をキャッチ
}).catch(function(error){
    console.error(error);
});

Promiseでネスト構造を作成してみる。

応用編としてプロミスを利用した、ネスト構造を作成してみます。

new Promise(resolve =>{
    setTimeout(() =>{
        console.log("1番目");
        resolve();
    },1000)//待ち時間を記述
}).then(() =>{
    return new Promise(resolve =>{
        setTimeout(() =>{
            console.log("2番目");
            resolve();
        },1000)//待ち時間を記述
    });
}).then(() =>{
    return new Promise(resolve =>{
        setTimeout(() =>{
            console.log("3番目");
            resolve();
        },1000)//待ち時間を記述
    });
});
0
1
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
1