Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Promise.prototype.then()

Esta tradução está incompleta. Ajude atraduzir este artigo.

This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

Resumo

O método then() retorna uma Promise. Possui dois argumentos, ambos são "call back functions", sendo uma para o sucesso e outra para o fracasso da promessa.

Sintaxe

p.then(quandoRealizada, quandoRejeitada);

p.then(function(valor) {
   // sucesso
  }, function(motivo) {
  // rejeitada
});

Parametros

quandoRealizada
Uma Function chamada quando a Promise é cumprida (Sucesso). Essa função tem um argumento, o valor do cumprimento.
quandoRejeitada
Uma Function chamada quando a Promise é rejeitada. Essa função tem um argumento, o motivo da recusa.

Descrição

Assim como o método .then()  e Promise.prototype.catch() retornam uma Promise, eles podem ser encadeados - uma operação chamada composition.

Exemplos

Usando o método then

var p1 = new Promise(function(resolve, reject) {
  resolve("Success!");
  // or
  // reject ("Error!");
});

p1.then(function(value) {
  console.log(value); // Success!
}, function(reason) {
  console.log(reason); // Error!
});

Encadeando

Já que o método then() devolve uma Promise, você pode facilmente encadeá-los.

var p2 = new Promise(function(resolve, reject) {
  resolve(1);
});

p2.then(function(value) {
  console.log(value); // 1
  return value + 1;
}).then(function(value) {
  console.log(value); // 2
});

Especificações

Especificações Status Comentários
domenic/promises-unwrapping Draft Standardization work is taking place here.
ECMAScript 6 (ECMA-262)
The definition of 'Promise.prototype.then' in that specification.
Release Candidate Initial definition in an ECMA standard.

Compatibilidade dos Browsers

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 32 24.0 (24.0) as Future
25.0 (25.0) as Promise behind a flag[1]
29.0 (29.0) by default
Não suportado 19 7.1
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support Não suportado 24.0 (24.0) as Future
25.0 (25.0) as Promise behind a flag[1]
29.0 (29.0) by default
Não suportado Não suportado iOS 8 32

[1] Gecko 24 has an experimental implementation of Promise, under the initial name of Future. It got renamed to its final name in Gecko 25, but disabled by default behind the flag dom.promise.enabled. Bug 918806 enabled Promises by default in Gecko 29.

Veja também

Etiquetas do documento e colaboradores

 Colaboradores desta página: lypborges
 Última atualização por: lypborges,