Home > Enterprise >  vuejs - asynchronous request and multiple .then explanation
vuejs - asynchronous request and multiple .then explanation

Time:10-05

actually, I couldn't understand the asynchronous concept when it comes to retrieve data from backend server using fetch method.

Why the result of this process is considered as eventual ?

sometimes I come accross examples containing multiple .then() which complicates things for me more and more, as on the code below

    return fetch(`URL to service`, {
      method: 'GET',
      credentials: 'include',
    }).then(resp => {
      if (!resp || !resp.ok) {
        throw new Error(this.$t('UnknownServerError'));
      } else {
        return resp.json();
      }
    }).then(data => {
      this.test = data || [];
    });

could you explain why this all about ?

CodePudding user response:

So when you use then, you're coupling the steps in a synchronize process. So if you have command.then(command2).then(command3). However, the chain itself is asynchronous so if you had the following:

command.then(command2).then(command3)
command4.then(command5).then(command6)

There's no guarantee which one will finish execution first. And if there's a long waiting process (waiting on a response, not waiting as it's executing CPU bound task), it can switch to working on commands in the second task.

  • Related