0
1

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.

javascript 同期処理メモ

Last updated at Posted at 2019-09-12
  • 同期処理

<script>
// 処理を順番に実行する
const processA =function() {
  return new Promise(function(resolve, reject) {
    console.log("processA");
    // 処理が終わったことを知らせる
    resolve();
  })
}


const processB = function() {
  return new Promise(function(resolve, reject) {
    console.log("processB");
    resolve();
  })
}


const processC = function() {
  return new Promise(function(resolve, reject) {
    console.log("processC")
    resolve();
  })
}

// .thenで後に続く処理を書く
processA()
  .then(processB)
  .then(processC)
</script>




<script>
/* for の場合 **************************************************/
function sleep(time) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, time);
    });
}


(async () => {
    const a = [1,2,3,4,5];
    // foreachだと非同期になってしまう
    for(let i of a) {
        // new Promiseオブジェクトをawaitすると待機可能になる
        await sleep(1000);
        console.log(i);
    }
})();
</script>
  • foreach内でawait
// いける
Array.foreach(async function(data, index){
    await 関数処理
});

// いける
Array.foreach(async (data, index) => {
    await this.関数処理
});

// 書き方は統一させたほうが良い

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?