Search code examples
javascriptnode.jspromiseelectronchain

How can promise chains assert that which value is from which return value?


I'm currently studying Electron in Action. I'm learning JavaScript on-the-go and this didn't come up in google so I'd thought I'd ask it in here. Imagine we have this code:

newLinkForm.addEventListener('submit', (event) => {
  event.preventDefault();
  const url = newLinkUrl.value;
  fetch(url)
    .then(response => response.text())
    .then(parseResponse)
    .then(findTitle)
    .then(title => storeLink(title, url))
    .then(clearForm);
});

in the first, and the fourth ring of the chain, we've gave a name to the return value of the zeroth, and the third function. But what if there are more than one return values? Do we create a list? Can we call two functions in a promise chain as in:

then(returnvalue1=>funct1, returnvalue2=>funct2)

Can we do that? Thanks for the response.


Solution

  • Second then argument is reserved for error handler, then(returnvalue1=>funct1, returnvalue2=>funct2) isn't a correct way ti handle return values.

    then callback receives the only one return value as a parameter, a value that previous then callback returns.

    In case values from different then need to be used together, they should be either passed through entire promise chain as array or object value and destructured:

    promise
    .then(foo => {
       const bar = 'bar';
       return [foo, bar];
     })
    .then(([foo, bar]) => {
      // can access both foo and bar
    })
    

    Or then should be nested to have access to the scope where necessary value is available:

    promise
    .then(foo => {
       const bar = 'bar';
    
       return Promise.resolve(bar);
       .then(bar => {
         // can access both foo and bar
       })
     })
    

    This is one of the problems that async..await solves.