News for hackers. Stuff that matters.
Re:ES6: The features I'm most excited about by haberman on Sunday July 05, 2015 @09:55PM (#9836190)
I've just been playing with Promises and like them a lot. But one thing I find strange is that ".then()" creates a new promise, but with no way to reject it.

ie. I can't write:

  return new Promise((resolve, reject) => {
    // Do some stuff, call resolve()/reject() on success/failure.
  }).then((step1Val, resolve, reject) => {
    // Do some stuff, call resolve()/reject() on success/failure.
    // But this doesn't actually work, because the "then" callback
    // doesn't get resolve/reject as args.
  });
Instead I'm having to write this as the following, which is more verbose:

  return new Promise((resolve, reject) => {
    // Do some stuff, call resolve()/reject() on success/failure.
  }).then(new Promise((resolve, reject) = {
    // Do some stuff, call resolve()/reject() on success/failure.
    // But this way I don't get access to step1Val.
  }));
Another bummer of this style is that that the second step doesn't get access to the first step's value.
Re:ES6: The features I'm most excited about by chncdcksn on Sunday July 05, 2015 @11:25PM (#9836564)
.then() does create a new promise. Return Promise.reject() in the fulfillment function to reject the new promise.

  somethingThatReturnsPromiseWithoutError()
    .then((res) => {
      return Promise.reject("some error");
    })
    .catch((err) => {
      console.log(err); // => some error
    });
Promise.resolve() and Promise.reject() return a promise resolved or rejected to the value passed in the first argument. Returning a promise in the fulfillment function passed to .then() chains the promises together.

  somethingThatReturnsPromise()
    .then((foo) => {
      return foo.bar;
      // Or if you like it more verbose
      return Promise.resolve(foo.bar);
      // Or pass bar to a function modifying bar that returns a promise
      return modifyBarReturnPromise(foo.bar);
    })
    .then((newBar) => {
      console.log(newBar);
    });
In your case, if you need step1Val in next promise chain, I personally do this, however people more familiar with promises may know of a better way to do it (maybe with something like Promise.all() or Promise.props() in the BlueBird library).

  somethingThatReturnsPromise()
    .then((first) => {
       doSomethingWithFirstAndReturnPromise(first)
         .then((second) => {
           console.log(first + second);
         });
    });
Re:ES6: The features I'm most excited about by mikekchar on Monday July 06, 2015 @02:33AM (#9837174)
It took me a while to understand this correct response because I couldn't understand the documentation for promises. For the benefit of any other person who was likewise confused...

then() returns a new promise resolved to the return value of the function. However, if that value is itself a promise, then it follows the promise chain and passes the eventual state to the next then()/catch() call.

Re:ES6: The features I'm most excited about by spion on Monday July 06, 2015 @04:32AM (#9837621)
You don't need resolve or reject. Just return the promise:

  .then(val => doSomeStuff())
Thats it. The resulting promise will get resolved/rejected based on the return result of doSomeStuff()

You can also use throw to reject a promise manually, or return Promise.reject()

  .then(val => {
    if (something) return successVal;
    else throw new Error("Failure");
  });
For more complex scenarios where I need the values from previous actions, I like the forgoing the chaining and using a join helper to unwrap any set of promises as needed:

  let url  = getUrl(resource);
  let data = url.then(url => fetch(url))
  let updateData = d => _.assign(d, {field: 'newVal'}
  let update = join(url, data, (url, data) => sendUpdate(url, updateData(data))
Re:ES6: The features I'm most excited about by seniorsassycat on Sunday July 05, 2015 @11:27PM (#9836569)
I like Jquery's Deferred better then ES6 Promise. Promises lack the `always` callback, they don't have any `progress` events.

The spec on mdn[0] doesn't mention asynchronous `then` or `catch` behavior. If the callback in Jquery `Deferred#then` returns a Deferred that deferred will be returned by `then`.

    // Basic async function, resolves after n milliseconds
    function wait(n) {
      var promise = $.Deferred();
      setTimeout(promise.resolve, n);
      return promise;
    }

    wait(10)
      .then(function() {
        console.log('first');  // prints first after 10 milliseconds
        return wait(10);
      })
      .then(function() {
        console.log('second'); // prints second after 20 milliseconds
        return 'done';
      })
You can 'flip' a failed promise by returning a resolve promise in the fail callback.

    var promise = $.Deferred();
    setTimeout(promise.reject, 100)

    promise.then(null, function () {
      return $.Deferred().resolve([]);
    }).done(function(arg) {
      console.log(arg); // Prints '[]'
    })
[0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Re:ES6: The features I'm most excited about by tracker1 on Monday July 06, 2015 @03:52AM (#9837497)
I don't see the problem...

    function doSomething() {
      return new Promise((resolve,reject)={
        setTimeout(reject,100);
      })
      .catch(() => [])
    }

    doSomething().then((arg) => console.log(arg));
Re:ES6: The features I'm most excited about by seniorsassycat on Monday July 06, 2015 @10:15AM (#9839211)
The problem may have just been the docs. They say .catch and .then can be composed but I didn't see any mention of the behavior.
[deleted]
Re:ES6: The features I'm most excited about by haberman on Sunday July 05, 2015 @10:30PM (#9836349)
> .then() does not create a new promise

The docs for Promise say that then() returns a promise. Are you saying it returns the original promise (ie. this)?

> But if your call to then isn't a Promise or a function that returns a Promise, your chain ends.

I don't think this is correct. The docs show examples of chains of then() calls where the intermediate function isn't returning a promise. See "chaining": https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

Re:ES6: The features I'm most excited about by cjbprime on Sunday July 05, 2015 @10:31PM (#9836356)
> .then() does not create a new Promise

It returns a promise, right?

  > var foo = Promise.resolve([1,2,3]).then(function() { return 5 })
  > foo
  < Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 5}
Re:ES6: The features I'm most excited about by rory096 on Sunday July 05, 2015 @11:09PM (#9836511)
I'd think it would return the original promise, for chaining.
Re:ES6: The features I'm most excited about by DCoder on Monday July 06, 2015 @01:33AM (#9836988)
No, it returns a new Promise that's already been resolved to the value you returned previously.
Re:ES6: The features I'm most excited about by cjbprime on Monday July 06, 2015 @10:00AM (#9839087)
Not quite :) See my paste above, it returns a new Promise in pending state that will return the value in the new then block ("5" here), possibly immediately. (i.e. pending for one event loop tick, then resolved)
Re:ES6: The features I'm most excited about by DCoder on Monday July 06, 2015 @10:37AM (#9839377)
Yes, you're right. My bad.
Re:ES6: The features I'm most excited about by 15155 on Sunday July 05, 2015 @10:01PM (#9836225)
async/await solves error handling and hanging onto values quite nicely.

IMO you should use Babel and take advantage.

Re:ES6: The features I'm most excited about by haberman on Sunday July 05, 2015 @10:18PM (#9836301)
I am using Babel already. Not sure I'm ready to dip into ES7 features though. ES6 feels bleeding-edge enough for me.
Re:ES6: The features I'm most excited about by grandalf on Sunday July 05, 2015 @11:07PM (#9836507)
link to example please
Re:ES6: The features I'm most excited about by 15155 on Monday July 06, 2015 @12:43AM (#9836827)

  async function foo() {
    try {
      const valueOne = await promiseReturningFunction();
      const valueTwo = await anotherAsyncFunction(valueOne);

      return valueTwo;
    } catch (err) {
      alert(err);
    }
  }

  foo(); //Returns a Promise.
----

In this example, I've sequenced the resolution of two promises (async functions return Promises when invoked)

If either of these Promises reject or throw an error, or if any of the code within the try {} block throws an error, the error will be caught inline in the catch block (one area only).

You can also see that both Promise's return values are in-scope and continually usable (vs. losing scope with 'then' chains).

Re:ES6: The features I'm most excited about by grandalf on Monday July 06, 2015 @01:29AM (#9836977)
I see. Not sure what the best practice is for the losing scope in then chains issue with promises. I ended up creating something along the lines of a message object designed for each chain, which felt like a smell.
Re:ES6: The features I'm most excited about by 15155 on Monday July 06, 2015 @02:24AM (#9837142)
Feels like an un-compiler-assisted State monad.

IMO threading an object through is probably the best method, unfortunately. You could use an Immutable Record or something to help keep it under control.

I would personally just use async/await to more explicitly handle the sequencing/binding.

Re:ES6: The features I'm most excited about by grandalf on Monday July 06, 2015 @08:08AM (#9838472)
Agreed. I think I'll refactor... thanks for the example.
Re:ES6: The features I'm most excited about by AgentME on Sunday July 05, 2015 @10:03PM (#9836235)
There is a way to reject it in the .then() callback. You just throw.
Re:ES6: The features I'm most excited about by haberman on Sunday July 05, 2015 @10:15PM (#9836290)
So in the first function you call reject, but in the second function you throw? I don't love the asymmetry.

Also how do you return a value from the second callback? Just return?

If throw and return work that way for then() functions, why not the same for the initial function?

Re:ES6: The features I'm most excited about by jkrems on Sunday July 05, 2015 @11:01PM (#9836483)
Because the initial one is where you'd interface (potentially) with non-promise code. E.g. in order to wrap a node-style function, you can't throw or return. But in general you shouldn't need to use `new Promise()`, that should in most cases be reserved to more general, low-level code (e.g. a promisify implementation).
Re:ES6: The features I'm most excited about by haberman on Sunday July 05, 2015 @11:25PM (#9836563)
I'm writing code against indexedDB (which doesn't use promises), but I want to expose promises to my callers. So I'm wrapping my indexedDB usage in Promises.

Also some of indexedDB doesn't seem like it would fit with promises, since some operations have 3 or more callbacks (onsuccess, onerror, onupgradeneeded).

Re:ES6: The features I'm most excited about by jbergens on Monday July 06, 2015 @04:37AM (#9837648)
There are a number of IndexedDb libraries that uses promises. However, there is or was a problem with how IndexedDb is specified to work that is not really compatible with promises. I'm not sure if they have fixed this yet. https://github.com/promises-aplus/promises-spec/issues/45#is...
Re:ES6: The features I'm most excited about by haberman on Monday July 06, 2015 @12:07PM (#9840110)
Interesting info, thanks for the pointer!

I can see the benefits of the indexedDb behavior: an open transaction is an exclusive resource, so leaving one dangling locks out other transactions. The auto-commit behavior means it's a lot harder to accidentally leave a transaction dangling. But it is unfortunate that this makes it not play nicely with promises.

Re:ES6: The features I'm most excited about by Bahamut on Sunday July 05, 2015 @11:09PM (#9836514)
Or better, Promise.reject
Re:ES6: The features I'm most excited about by loganfsmyth on Monday July 06, 2015 @02:01AM (#9837061)
Both are useful, but I'd hesitate to call it better. What makes you say it is better?
Re:ES6: The features I'm most excited about by Bahamut on Monday July 06, 2015 @03:18AM (#9837348)
It makes explicit that the intention that a promise should be rejected, as opposed to a throw where one might reasonably expect an exception of some sort.
Re:ES6: The features I'm most excited about by inglor on Sunday July 05, 2015 @11:35PM (#9836599)
You can reject inside a `then` by `throw`ing an error, like synchronous try-catch.
Re:ES6: The features I'm most excited about by regecks on Sunday July 05, 2015 @10:03PM (#9836233)
Throw an Error to reject it.