Sample of promises synchronization

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.8 kB
4
Indexable
Never
  function customlog(message, marker) {
    console.log(new Date().toISOString() + ' -- ' + (marker ? '['+marker+'] ' : '') + message)
  }
  
  function res(ms) {
    // set logging marker
    const marker = 'res-'+ms;
    
    // log setup of promise object
    customlog('Setting up promise going to resolve in '+ms+ ' miliseconds.', marker)
  
    return new Promise((resolve,reject) => {        
        // set the timeout
        setTimeout(() => {
          // actions after timeout
          customlog('Resolving promise after ' + ms + ' miliseconds.', marker)
          resolve(ms) 
        }, ms);
    });
  } 
  
  function rej(ms) {
    // set logging marker
    const marker = 'rej-'+ms;

    // log setup of promise object
    customlog('Setting up promise going to reject in '+ms+ 'miliseconds.', marker)
        
    return new Promise((resolve,reject) => {
        // set the timeout
        setTimeout(() => { 
          // actions after timeout
          customlog('Rejecting promise after ' + ms + ' miliseconds.', marker)
          reject(ms)
        }, ms);
    });
  }
  
  async function test1() {
    const promise1 = res(3000)
    const promise2 = res(2000)
    const promise3 = res(1000)

    const value1 = await promise1
    const value2 = await promise2
    const value3 = await promise3
    
    customlog('Function test1 finished.')
  }

  async function test2() {
    const promise1 = res(3000)
    const value1 = await promise1
    
    const promise2 = res(2000)
    const value2 = await promise2
    
    const promise3 = res(1000)
    const value3 = await promise3
    
    customlog('Function test2 finished.')
  }
  
  async function test3() {
    res(3000)
    res(2000)
    res(1000)
    
    customlog('Function test3 finished.')
  }