console.log返回挂起的承诺,而不是实际数据

时间:2017-07-20 12:34:18

标签: javascript json typescript asynchronous

所以我有这个文件:

 'use strict'
import * as moment from "moment";
import { Report} from "./Report";
import { Timeframe} from "./Timeframe";
import { ReportComparison } from "./ReportComparison";

function test(firstFrom: string, firstTo: string, secondFrom: string, secondTo: string) {


    var pastReport = new Report(new Timeframe(moment(firstFrom), moment(firstTo)));
    var laterReport = new Report(new Timeframe(moment(secondFrom), moment(secondTo)));

    var reportComparison

    function getData(pastReport: Report, laterReport: Report) {

        var later = function() {
            return new Promise((resolve, reject) => {
                laterReport.fetchData(data => resolve(data));
            });
        };

        var past = function() {
            return new Promise((resolve, reject) => {
                pastReport.fetchData(data => resolve(data));
            });
        };

        return Promise.all([later(), past()]).then(() => {
            laterReport.sort();
            reportComparison = new ReportComparison(pastReport, laterReport);

            return {
                pastReport: {
                    projects: reportComparison.pastReport.projects,
                    timeFrame: reportComparison.pastReport.timeframe,
                    totalAutomatedRuns: reportComparison.pastReport.totalAutomatedRuns,
                    totalManualRuns: reportComparison.pastReport.totalManualRuns

                },
                laterReport: {
                    projects: reportComparison.laterReport.projects,
                    timeFrame: reportComparison.laterReport.timeframe,
                    totalAutomatedRuns: reportComparison.laterReport.totalAutomatedRuns,
                    totalManualRuns: reportComparison.laterReport.totalManualRuns
                },
                trends: reportComparison.trends
            }

        });

    }

    return getData(pastReport, laterReport).then((res) => {
        return res;
    });

}



console.log(test("20170707", "20170707", "20170710", "20170710"))

现在,console.log返回Promise { <pending> }而不是我想要返回的实际值(JSON对象)。我正确接近这个异步代码吗?我可以使用什么解决方案将JSON作为值返回,而不是挂起的承诺。

2 个答案:

答案 0 :(得分:2)

方法 test 确实会返回一个promise。要访问数据,请调用.then()函数。

<li ng-repeat="p in filteredPeople">
     <h4>{{p.name}} ({{p.age}}) id: {{p.id}}</h4>
</li>

答案 1 :(得分:2)

是的,只有当你从这里回复承诺时,你才会得到承诺

  

返回getData(pastReport,laterReport).then((res)=&gt; {

    return res; //Do callback here...
});

这是你的主要回报,我的意思是测试函数的返回值,你只返回了promise,并注意你从那里返回的内容只会在该函数中返回,因此它不会反映在test的返回中值。 如果您不想更改代码,可以使用回调

或将其更改为

  

返回getData(pastReport,laterReport)

并像这样进行测试

test(...).then((res)=>{ 
})
Or like this
var a = await test(...)
then test will return data.