【问题标题】:Usage of return in JavaScript promises在 JavaScript Promise 中使用 return
【发布时间】:2019-08-18 00:59:09
【问题描述】:

我正在努力更好地理解承诺。 我正在对 API 进行异步调用,然后根据响应,我想做更多操作,为此我使用以下 2 种方法:

方法一:

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() 已经在返回值,那么在调用getValueOfA()getValueOfB() 之前是否还需要使用return 才能使用then

方法 1 不使用 return,而方法 2 使用 return

感谢澄清

【问题讨论】:

  • 代码不等价,因为在方法 1 中,bOutput 将是未定义的,因为上一步没有返回 getValueOfB() 。只有当aOutput 已经是一个promise 时才有意义,因为否则getValueOfA() 将不会返回您可以将.then() 链接到的东西。所以答案是:如果您希望返回的内容可用作链接到它的下一个 .then() 的参数,则始终必须在 .then() 处理函数中返回。
  • 如果 getValueOfA() 返回一个承诺,那么如果我在调用 getValueOfA() 时添加另一个返回,因为它已经返回,会不会有问题?
  • 为了清楚起见,aOutputbOutput 最好命名为 aPromisebPromise。如果它们不是 thenable(很可能是 Promises),那么 getValueOfA().then(...)getValueOfB().then(...) 会抛出。
  • 不,每个函数都可以(并且可能应该)有自己的返回值。这(通常)包括 .then() 回调函数。
  • 回报至关重要。 .then() 回调函数传递值(或传递最终将传递值的 Promise)的唯一方法是让该回调返回。如果它没有返回任何东西,那么它将一如既往地返回undefined。无论返回什么都会被传递到承诺链的下一个阶段。

标签: javascript jquery asynchronous promise callback


【解决方案1】:

这与承诺没有直接关系。

function getABValues() 在方法 1 中没有返回语句。它将返回undefined

方法 2 中的

function getABValues() 有一个 return 语句。它将返回评估 getValueOfA().then(something).then(something) 的结果,这将是一个承诺。

所以方法 2 将允许您:

getABValues().then(do_something_with_those_values);

【讨论】:

    【解决方案2】:

    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

    【讨论】:

    • 完美。现在清除。这就是我要找的
    猜你喜欢
    • 2018-12-28
    • 2016-04-12
    • 2016-12-07
    • 1970-01-01
    • 2021-06-13
    • 2018-09-28
    相关资源
    最近更新 更多