Assign value from successful promise resolve to external variable

前端 未结 5 1636
陌清茗
陌清茗 2020-12-23 19:23

I have a pretty silly problem. Consider the following:

vm.feed = getFeed().then(function(data) {return data;});

getFeed() retu

5条回答
  •  [愿得一人]
    2020-12-23 20:19

    The then() method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:

    getFeed().then(function(data) { vm.feed = data;});
    

    The then() function returns the promise with a resolved value of the previous then() callback, allowing you the pass the value to subsequent callbacks:

    promiseB = promiseA.then(function(result) {
      return result + 1;
    });
    
    // promiseB will be resolved immediately after promiseA is resolved
    // and its value will be the result of promiseA incremented by 1
    

提交回复
热议问题