Promise in JavaScript

12.10.19

Promise in javascript is used for asynchronous operations

For example

function getInfo(url){

    return new Promise((resolve, reject) => {
       
        $.ajax(url)
            .done(response => {
                	resolve(response);
                })
            .fail((xhr, textStatus) => {

                reject(textStatus);
                 
            });
                  
    });
}

let loading = true;

getInfo('file1.txt')
.then( data => {
 	$('.container').append('<p>' + data + '</p>')
   return getInfo('file2.txt');
})
.then( data => {
   return getInfo('file3.txt');
})
.then(() => {
    console.log('ok');
})
.catch(error => {
    console.log('something went wrong: ' + error);
})
.finally(() => {
	 loading = false;
});

In resolve, we pass the data on success and they will be accepted in the then method. In reject, we pass the data on error and they will be accepted in the catch method. The finally method will work at the end of the chain anyway.

The Promise.all (iterable) method returns a promise that will be fulfilled when all promises passed as an enumerated argument are fulfilled or any of the transferred promises is rejected.

let p1 = new Promise((resolve, reject) => {
	setTimeout(() => {

		resolve('some data');

	}, 500);
});

let p2 = Promise.resolve(5);

let p3 = new Promise((resolve, reject) => {
	setTimeout(() => {

		resolve('other data');

	}, 1000);
});

Promise.all([p1, p2, p3]).then(values => { 
  console.log(values); 
});

blog comments powered by Disqus