【问题标题】:Get Promise data out of it Javascript从中获取 Promise 数据 Javascript
【发布时间】:2015-05-06 21:08:21
【问题描述】:

我试试这个:

var result = [];
promise.then(function (data) {
  result.push(data);

});
console.log(result)

结果数组为空。有没有办法让它脱离承诺?

【问题讨论】:

  • promise 是什么显示更多代码。你在哪里定义promise
  • 该死的。通常我们通过告诉使用承诺来回答这个问题......
  • @Edwin 没关系
  • 你在哪里运行你的代码?你在使用像 babel-js 这样的工具吗?你在标记什么?
  • 算了,我没听明白,我以为他在问为什么result是空的

标签: javascript arrays promise


【解决方案1】:

不,you can't.

promise 的重点是允许简单的操作链接,其中一些是异步的。

你可以这样做

var result = [];
promise.then(function (data) {
    result.push(data);
}).then(function(){
    console.log(result)
});

我建议你阅读this introduction to promises

【讨论】:

    【解决方案2】:

    Promise 有时被称为 futuresfuture values。您不能直接从承诺中获得价值,但您可以获得未来价值的承诺,如下所示。

    var futureResult = promise.then(function (data) {
        var result = [];
        result.push(data);
        return result;
    });
    
    futureResult.then(function (result) {
        console.log(result);
    });
    
    futureResult.then(function (result) {
        console.log('another logger');
        console.log(result);
    });
    

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      相关资源
      最近更新 更多