Help us understand the problem. What is going on with this article?

javascript 同期処理メモ

  • 同期処理
<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.関数処理
});

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away