如何将承诺的返回值分配给变量?

how to assign the returned value of a promise to a variable?

已编辑为要复制的评论 我引用自:[How do I return the response from an asynchronous call?

Promises are containers for future values. When the promise receives the value (it is resolved) or when it is cancelled (rejected), it notifies all of its "listeners" who want to access this value.

这个问题是关于如何return承诺中包含的值。 答案对我很有用,因为它阐明了不可能 return 值,而是 访问 中的值承诺函数。

有关该主题的其他有用资源,请参见:

原题下方:


能否请您帮助理解如何从承诺中获取价值以及这两个示例之间的区别?

//I have a simple ajax call like:

var fetch = function(start_node, end_node) {
var apiEndpoint = 'localhost/nodes/';
var loadurl = apiEndpoint+start_node+'/'+end_node;
return $.ajax({
    url: loadurl,
    type: 'GET',
    dataType: 'json',
    jsonpCallback: 'json'

  });

};
// Then I processed results in something like:
    var getResult = function(data) {
      // do smtg with data
      var result = {'myobject' : result_from_data}
      return result
    }

最后我想给它分配结果。

以下有效,但我认为它浪费了承诺的概念,因为结果被分配给在它之前声明的全局变量:

var r;  
fetch('val1','val2')
.then(function(data){
  r = getResult(data);
})

下面将 promise 函数分配给 res

var res = fetch('val1','val2')
.done(function(data){
  return getResult(data);
})

您能否说明如何将结果 'myobject' 传递给变量 res,而不是 promise 本身?

我也试过:

var res = $.when(fetch('val1','val2'))
.done(function(data){
  return getResult(data);
})

但没有成功。

你必须使用全局变量技巧,或者接受使用保存为承诺的技巧。

var getStuff = $.when(req1,req2).then(function(data1,data2) { return data1.concat(data2); });

//the variable getStuff is now a promise and any .then chained 
//to it will have data1.concat(data2) passed to it as an argument

getStuff
  .then(function(data1Data2) {
    console.log(data1Data2);
  });

//the next time you want to use it, you have to use the same promise-interface with .then
getStuff
  .then(function(data1Data2) {
    console.log(data1Data2);
  });