【问题标题】:Node.JS async function running forever no resultNode.JS 异步函数永远运行没有结果
【发布时间】:2020-12-14 02:58:52
【问题描述】:

我不熟悉 JS 中的 async / await 和 promises 等。我正在尝试构建一些实际上似乎可以工作的软件。但是,一个函数没有完成,并且似乎永远运行而没有返回结果。这是我的代码:

module.exports.visit = (val) => {

        let visit_date = Date.now();
        let data_json;
        let insert;

        client.get(val)
        .then( (data) => {
                data_json = JSON.parse(data);
                data_json.count += 1;
                data_json.last_visited = visit_date;
                insert  = JSON.stringify(data_json);
                client.set(val,insert);
                console.log(insert);
                return data_json.url;
        })
        .catch((err) => {
                console.log(err);
        });
}

调用这个函数的函数(为了返回url):

async function visitor() {
        // also doesn't work with let a = await helpers.visit('6q9ootm8p7');
        let a = helpers.visit('6q9ootm8p7');
        return a;
        }

visitor();

如果有人能指出我相同的方向,我将非常感激。

【问题讨论】:

    标签: node.js asynchronous callback


    【解决方案1】:

    helpers.visit 必须返回一个承诺。目前,它是无效的。试试:

    return client.get(val)
      .then(() => {
        // provide your code here, and return the data
        return ... ;
      })
      .catch(error => {
        console.error(error);
    
        // if you catch an error, you should provide your result data too
        return ... ;
      })
    ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多