Использование возврата в обещаниях JavaScript - PullRequest
0 голосов
/ 27 марта 2019

Я пытаюсь лучше понять обещания. Я делаю асинхронный вызов API, а затем, основываясь на ответе, хочу сделать еще несколько операций, для этого я использую следующие 2 подхода:

Подход 1:

function getABValues(){
     getValueOfA() /*this returns aOutput*/
     .then(function (aOutput){
      getValueOfB() /*this returns bOutput*/
     })
     .then(function (bOutput){
      console.log(bOutput);
     })
    }

Подход 2:

function getABValues(){
     return getValueOfA() /*this returns aOutput*/
     .then(function (aOutput){
      return getValueOfB() /*this returns bOutput*/
     })
     .then(function (bOutput){
      console.log(bOutput);
     })
    }

Вот функции getValueOfA () и getValueOfB ():

getValueOfA ()

function getValueOfA(){
 return aOutput;
}

getValueOfB ():

function getValueOfB(){
 return bOutut; 
}

Если вы заметили, getValueOfA() и getValueOfB() уже возвращают значения, нужно ли мне использовать return при вызове getValueOfA() и getValueOfB() перед использованием then.

Подход 1 не использует return, а подход 2 использует return.

Спасибо за разъяснение

Ответы [ 2 ]

4 голосов
/ 27 марта 2019

Это не имеет ничего общего с обещаниями.

function getABValues() в подходе 1 не имеет оператора возврата.Он вернет undefined.

function getABValues() в подходе 2 имеет оператор возврата.Он вернет результат оценки getValueOfA().then(something).then(something), который будет обещанием.

Так что подход 2 позволит вам:

getABValues().then(do_something_with_those_values);
1 голос
/ 27 марта 2019

const API = {
  ids: 0,
  get: function( value ) {
    return new Promise(function( resolve, reject ) {
      const timer = Math.random( Math.random() * 2 );
      setTimeout(function() {
        API.ids += 1;
        resolve([{ "id": API.ids, "value": value }]);
      }, timer );
    });
  }
};
// The mock API will give us a promise object.
// We want to return that promise object.
// So we can use the value of the promise in .then()
const getValueOfA = function() {
  return API.get( 'value A' );
};
const getValueOfB = function() {
  return API.get( 'value B' );
};

// We want to chain both API to resolve in order.
const getABValues = function() {
  // If we do not return, we cannot use getABValues().then( ... )
  // Outside of this function.
  return getValueOfA()
    // If we did not return inside getValueOfA(), we would not have the API promise.
    // And then this line will throw an error
    // Since undefined does not have a method called .then()
    .then(function( resolvedValueOfPromiseA ) {
      // We can use resolvedValueOfPromiseA here, which will be the value:
      // [{"id":1,"value":"value A"}]
      console.log( 'inside getValueOfA().then( ... )' );
      console.log( JSON.stringify( resolvedValueOfPromiseA ));
      // Return getValueOfB() so we can use the resolvedValueOfPromiseB
      return getValueOfB();
      // We could also use
      //
      // return getValueOfB( resolvedValueOfPromiseA );
      //
      // If we change the getValueOfB() function to have a aprameter and use it.
      // Then we can use the value of resolvedValueOfPromiseA
      // Inside getValueOfB()
    })
    .then(function( resolvedValueOfPromiseB ) {
      console.log( 'inside getValueOfA().then( ... ).then( ... )' );
      console.log( JSON.stringify( resolvedValueOfPromiseB ));
      return resolvedValueOfPromiseB;
    });
};
// Use the function on the outside.
// We can call .then() since getABValues() returns the entire promise chain.
getABValues()
  .then(function( resolvedValueOfPromiseBReturnedByThen ) {
    console.log( 'inside getABValues().then( ... )' );
    console.log( JSON.stringify( resolvedValueOfPromiseBReturnedByThen ));
  });
// Notice how here we only have the result of getValueOfB()
// Since we did not do anything with resolvedValueOfPromiseA in the .then() function
// THat ahd access to resolvedValueOfPromiseA
...