Promise in JavaScript

06.07.19

JavaScript promises

function doSomething(data){
    return new Promise(function(resolve, reject){
         
        if(data)
            resolve('success');
        reject('fail');
        alert('test');
         
    });
}
 
doSomething(1)
    .then(suc => console.log(suc))
    .catch(fail => console.log(fail));

And a slightly more illustrative example.

function getInfo(url){
 
        return new Promise((resolve, reject) => {
           
            $.ajax(url)
                .done(response => {
                    resolve(
                        $('.container').append('<p>' + response + '<p>')
                        );
                    })
                .fail((xhr, textStatus) =>{
 
                    reject(textStatus);
                     
                });
                      
        });
    }
 
    getInfo('file1.txt')
    .then(()=>{
       return getInfo('file2.txt');
    })
    .then(()=>{
       return getInfo('file3.txt');
    })
    .then(()=>{
        console.log('ok');
    })
    .catch(error=>{
        console.log('something went wrong: ' + error);
    });
blog comments powered by Disqus