js-asyc-promise-reading-summary

nested promise

  1. Request code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const makeRequest = async() => {
    const response = await fetch(url);
    if(response.needAnotherRequest){
    const secondResponse = await makeAnotherRequest(reponse);
    console.log(secondResponse);
    return secondResponse;
    }
    console.log(response);
    return response;
    }
  2. sync a list post Request:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    let promise = Promise.resolve();
    let posts = [{}, {}, {}];

    posts.forEach(post => {
    //construct a new promise and replace the old one
    //promise return the resove callback
    promise = promise.then(()=>{
    return db.insert(post);
    });
    });

    promise.then(()=>{
    ///all you post request has been make one by one
    });

if you want to make it concurrently post, it will looks like:

1
2
3
posts.forEach(post=>{
promise = promise.then(db.insert(post));
})

// this might not be correct.

sequential vs parallism

promise.all and yield all in generator as well as generate a list of promise and promise all of them immedieately