【问题标题】:nodejs undefined asynchronousnodejs未定义异步
【发布时间】:2018-08-23 02:05:09
【问题描述】:
        console.log("validate");

        var team = getItem(place, function(err,data){
          if(err){
             console.log("getItem err");
             console.log(err);
          } else {
              console.log("getItem ok");
              console.log("teamnaam is:" + data);

              return data;
          }
        });

    console.log("test" + team);
    return buildValidationResult(false, 'place', 'This team is' + team);

我收到一个 undefined for team 的值。如何从 getItem 中获取数据。

这些是console.log在日志文件中的顺序。 证实 测试未定义 获取项目确定 teamnaam 是:Ramon 最好的

看来这两条线很快就要开始了: console.log("测试" + 团队); return buildValidationResult(false, 'place', 'This team is' + team);

谁能帮帮我?

【问题讨论】:

  • Nodejs 是异步的,所以这里需要使用 Promise
  • getItem() 是做什么的?

标签: node.js undefined


【解决方案1】:

试试这个

function name(cb) {
    getItem(place, function (err, data) {
        if (err) {
            console.log("getItem err");
            cb(err);
        } else {
            console.log("getItem ok");
            console.log("teamnaam is:" + data);
            cb(null, buildValidationResult(false, 'place', 'This team is' + data));
        }
    });
}

// call

name((err, data) => {
    if (err) {
        console.log("getItem err", err);
    } else {
        console.log("data", data);
    }
});

【讨论】:

  • 这是来自另一个函数的调用,需要返回
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 2015-05-29
  • 2019-01-28
相关资源
最近更新 更多