async, await, and promises


working with nonblocking computation

Abel Sanchez, John R Williams

nonblocking computation

Write order?


setTimeout(function(){
    console.log('1');
},3000);

setTimeout(function(){
    console.log('2');
},0);

console.log('3');
					

How do we control the execution order?

  • Promises
  • async
  • await

Promises, ex 1


var p = new Promise(function(resolve,reject){
    setTimeout(function(){
        resolve('Hello 1');
    },3000);
});

p.then(function(msg){
    console.log(msg);
});

console.log('Hello 2');
					

Promises, ex 2


var p1 = new Promise(function(resolve,reject){
    setTimeout(function(){
        resolve('Hello 1');
    },3000);
});

var p2 = new Promise(function(resolve,reject){
    setTimeout(function(){
        resolve('Hello 2');
    },1000);
});

p1.then(function(msg){
    console.log(msg);
    return 'P1 done!';
})
.then(function(msg){
    p2.then(function(msg){
        console.log(msg);
    }); 
    console.log(msg);
});

console.log('Hello 3');
					

async


function timeout(milliSeconds){
    console.log('In timeout'); 
    return new Promise(function(resolve){
        setTimeout(resolve,milliSeconds)
    });
}

async function run(x) {
    await timeout(3000);
    return 'Timeout Finished!';
}

run(10).then(function(msg){
    console.log(msg)
});

console.log('Last Line');
					

async, await, & promise


function resolveAfter3Secs(x) {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log('01 - ' + new Date());          
        resolve(x+10);
      }, 3000);
    });
}

async function run(x) {
    var response = await resolveAfter3Secs(x);
    console.log('02 - ' + new Date());
    return response;
}

run(10).then(response => {
    console.log(response);
    console.log('03 - ' + new Date());  
});

console.log('04 - ' + new Date());
					

async request


var request = require('request');
var url = 'http://student.mit.edu/catalog/m1a.html';

function makeRequest(url) {
    // return promise
    return new Promise(function(resolve,reject) {
        function callback(error, response, body) {
            resolve(body);
        }
        request(url, callback);
    });
}

var run = async () => {
    console.log('make: ' + await makeRequest(url))
    return "done"
}
  
run().then((result) =>{
    console.log(result);
});
					

node-fetch


var fetch = require('node-fetch');

var makeRequest = async function (url) {
    var response = await fetch(url);
    var text     = await response.text();
    return text;
};  

var url = 'http://student.mit.edu/catalog/m1a.html';

makeRequest(url).then((text) =>{
    console.log(text);
});    
					

fetch multiple urls, write response to file system


var fetch = require('node-fetch');
var fs    = require('fs');
var urls  = ['http://student.mit.edu/catalog/m1a.html'];

const writeFile = (path, data, opts = 'utf8') =>
    new Promise((resolve, reject) => {
        fs.writeFile(path, data, opts, (err) => {
            if (err) reject(err)
            else resolve()
    })
})

var makeRequest = async function (url,counter) {
    var response = await fetch(url);
    await writeFile('data/' + counter + '.html', await response.text());
    return 'done - ' + counter;        
};  

urls.forEach(function(url,i){
    makeRequest(url,i).then((result) =>{
        console.log(result);
    });    
})
					

THE END