首页 > 解决方案 > 如何让程序等待一个函数在 Node 中完成运行?

问题描述

我有这两个功能:一个分析一些数据,另一个提供一些数据。在这里,分析数据的人翻译给定的文本并通过 IBM 的 Watson 上的 NLU 模型运行它。现在我只想将所有分析结果存储到 1 个单个数组中并将其记录在控制台中。
我的代码:

const analyzeTweet = function(tweet){
    return new Promise((resolve,rejects)=>{
        translator(tweet).then(translation => {
            const options = {
                text: translation.text,
                features: {
                    entities: {model:auth.model},
                    relations:{model: auth.model}
                },
            };
            nlu.analyze(options).then(responce => {
                resolve(responce.result);
            });
        });
    });
    
}

aggregate();

function aggregate(){
    var analysis = []
    incoming.forEach(tweet => {
        result = analyzeTweet(tweet).then(result => {
            analysis.push(result);
        })
    });
    console.log(analysis);
}

incoming这里无关紧要

问题是当我运行脚本时,我得到这个输出:

[]

什么可能是错的或者我做错了什么。我需要深入学习任何概念吗?

标签: javascriptnode.jsarrayspromise

解决方案


推荐阅读