How to use Bluebird promise library in the browser

Let me give you a few examples:

A basic one:

Here we have function that upload a file to the server.

function uploadFile(file, uploadId) {

return new Promise(function (resolve, reject) {

var formData = new FormData();

// all though allFiles, upload one file at a time

formData.append('bp', file);
formData.append('uploadId', uploadId);

// console.log(uploadId);

$.ajax({
url: '/api/bp-upload/new-bp-file',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
// alert(data);
// console.log(data);
resolve(data);
},
error: function (xhr, textStatus, error) {
console.log('error in uploadFile', error);
reject(new Error(error))
}
});
})

}

Here is another example. It executes one promise after another. The allFiles is a array of files to be uploaded (html File object that generated by a html input field)

var uploadAllFilesPromise = Promise.map([file1, file2], function (file) {
return uploadFile(file, uploadId)
}).then(function () {
showSuccessAlert();
}).catch(function (e) {
alert(serverErrorMessage);
}).finally(function () {
// show preloader
$('.preloader-wrapper').removeClass("active");
$('button.submit').attr('disabled', false); //reenable submit button in case of server error

});

What is the map here? Here, promise generate a promise for each file in the array and pass that into a anonymous function, which returns a promise too. It will generate a array of promises, and when all promises resovles, it goes to the then.

We also have a catch here for display error messages. And a finally clause to executes no matter what. There, we hide the preloader and make the submit button enabled again.