Skip to content

Instantly share code, notes, and snippets.

@RinatMullayanov
Last active September 18, 2015 11:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RinatMullayanov/6f86cf109e83e1b1aec1 to your computer and use it in GitHub Desktop.
Save RinatMullayanov/6f86cf109e83e1b1aec1 to your computer and use it in GitHub Desktop.
Notes about promises
function updateTask(oldTask, newTask) {
var promise = new Promise(function (resolve, reject) {
resolve({status: 'success'});
// resolve(Error('some error'));
});
return promise;
}
var postFile = function(name, file) {
var deferred = $q.defer();
var form = new FormData();
form.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', apiUrl + name, true);
xhr.onload = function(e) {
if (e.target.status == 200) {
deferred.resolve();
} else {
deferred.reject(e.target.status);
}
if (!$rootScope.$$phase) $rootScope.$apply();
};
xhr.send(form);
return deferred.promise;
};

API

Based on stackoverlow

We have a problem with promises

У нас проблема с промисами

Tips

Асинхронный JavaScript. Прошлое, настоящее и будущее

It's pretty straightforward with some simple rules:

  • Whenever you create a promise in a then, return it - any promise you don't return will not be waited for outside.
  • Whenever you create multiple promises, .all them - that way it waits for all the promises and no errors from any of them are silenced.
  • Whenever you nest thens, you can typically return in the middle - then chains are usually at most 1 level deep.
  • Whenever you perform IO, it should be with a promise - either it should be in a promise or it should use a promise to signal its completion.

And some tips:

  • Mapping is better done with .map than with for/push - if you're mapping values with a function, map lets you concisely express the notion of applying actions one by one and aggregating the result.
  • Concurrency is better than sequential execution if it's free - it's better to execute things concurrently and wait for them Promise.all then to execute things one after the other - each waiting before the next.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment