user5848619
user5848619

Reputation:

How does the promise then works?

I am trying to print all asynchronous calls in a sequence using promise. But i didn't understand whether then implicitly returns a promise or we should explicitly return it.

 function fakeAjax(url,cb) {
        var fake_responses = {
          "file1": "The first text",
            "file2": "The middle text",
            "file3": "The last text"
        };
        var randomDelay = (Math.round(Math.random() * 1E4) % 8000) + 1000;

        console.log("Requesting: " + url);

        setTimeout(function(){
            cb(fake_responses[url]);
        },randomDelay);
    }

    function output(text) {
        console.log(text);
    }

    // **************************************

    function getFile(file) {
        return new Promise((resolve, reject)=>{
            fakeAjax(file,resolve);
        })
    };


    let p1= getFile('file1');
    let p2= getFile('file2');
    let p3= getFile('file3');
    p1.then(output)  // how does this code work? output doesn't return any promise, but  still we can chain it with next .then()
    .then( ()=> p2)
    .then(output)
    .then(()=>p3)
    .then(output)
    .then(()=>output('complete'))

Upvotes: 0

Views: 87

Answers (1)

kiddorails
kiddorails

Reputation: 13014

then returns a promise enabling you to chain the functions that way. It implicitly converts takes the return value of output as the next resolution, and then makes it available in next then. In your case, it will be undefined.

Below is slight modification of your snippet, where I'm showing how then can enable you to create new Promise on the fly based on return value of last promise's resolution.

Here, in output method, after console.log, I have returned the value. Try running the snippet to see it in action.

function fakeAjax (url, cb) {
  var fake_responses = {
    'file1': 'file2',
    'file2': 'file3',
    'file3': 'The last text'
  }
  var randomDelay = 500

  console.log('Requesting: ' + url)

  setTimeout(function () {
    cb(fake_responses[url])
  }, randomDelay)
}

function output (text) {
  console.log(text)
  return text; // return the value
}

// **************************************

function getFile (file) {
  console.log('creating prommise for', file)
  return new Promise((resolve, reject) => {
    fakeAjax(file, resolve)
  })
}

var p1 = getFile('file1')
p1.then(output)
  .then(getFile)
  .then(output)
  .then(getFile)
  .then(output)

From the documentation:

The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.

If one or both arguments are omitted or are provided non-functions, then then will be missing the handler(s), but will not generate any errors. If the Promise that then is called on adopts a state (fulfillment or rejection) for which then has no handler, a new Promise is created with no additional handlers, simply adopting the final state of the original Promise on which then was called.

Upvotes: 1

Related Questions