Skip to content

Instantly share code, notes, and snippets.

@teppeis
Created April 4, 2015 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teppeis/3e1cfd9b6f17ed49db85 to your computer and use it in GitHub Desktop.
Save teppeis/3e1cfd9b6f17ed49db85 to your computer and use it in GitHub Desktop.

条件3のreturn Promise.resolve()はあっても無くても実行結果は変わらない。

function asyncFunc(msg, callback) {
  setTimeout(function() {
    console.log(msg);
    callback();
  }, 0);
}

var condition1 = false;
var condition2 = false;

Promise.resolve()
    .then(function(){
        if(condition1){
            // 条件1 単独のPromise
            return new Promise(function(fulfilled, rejected){
                asyncFunc('1', fulfilled);
            })
        }else if(condition2){
            // 条件2 Promise2つを直列化
            return Promise.resolve()
                .then(function(){
                    return new Promise(function(fulfilled, rejected){
                      asyncFunc('2-1', fulfilled);
                    })
                })
                .then(function(){
                    return new Promise(function(fulfilled, rejected){
                      asyncFunc('2-2', fulfilled);
                    })
                })
        }else{
            // 条件3 何もしない
            console.log('3');
            // return Promise.resolve(); これは不要
        }
    })
    .then(function(){
        return new Promise(function(fulfilled, rejected){
            asyncFunc('4', fulfilled);
        })
    });

実行結果

3
4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment