在node.js中返回带有async / await的对象

时间:2017-09-15 17:53:15

标签: node.js async-await

所以我正在玩node.js并尝试将一些数据从函数推送到对象。使用正则表达式正确解析所有内容,我想我只是不明白如何正确实现我正在做的事情。在我解析游戏数据后,我在json对象上得到了未定义。

const diplo = `!report Game Type: Diplo
1: <@12321321421412421>
2: <@23423052352342334>
3: <@45346346345343453>
4: <@23423423423523523>`


var diplo_data = {players:[]};

async function gameType(game) {
    let data = {};
    let game_types = [{id: 1, name: 'Diplo'}, {id: 2, name: 'Always War'}, {id: 3, name: 'FFA'}
        , {id: 4, name: 'No Diplo'}, {id: 5, name: 'Team'}, {id: 6, name: 'Duel'}, {id: 7, name: 'No War'}];
    let o = {}
    let reType = /!report Game Type:\s+?(\d|\w+)\s?(\w+\s?(\w+)?)?\n/gi
    let match = reType.exec(game)
    if(match[1]){
        for (var j = 0; j < game_types.length; j++) {
            if ((game_types[j].name).toLowerCase() === (match[1]).toLowerCase()) {
                data.type = game_types[j].id;
                break;
            }
        }
    }
    if(match[2]){
        data.moddifier = match[2]
    }
    console.log(data)
    await (data)
}

async function main() {

    console.log("Reading diplo data...\n\r")
    try {
        diplo_data = await gameType(diplo)
        console.log(diplo_data)
    } catch (err) {
        return 'No game type!';
    }        
}

main();

1 个答案:

答案 0 :(得分:6)

要修复代码中的错误,您必须在return之前添加await (data)语句:

async function gameType(game) {
  ...
  return await (data);
}

但主要问题是为什么你在那里使用async/await gameType不是异步函数,它不包含任何异步调用。它应该声明为常规同步函数:

function gameType(game) {
   ...
   return data;
}

调用main的函数gameType也应该在没有async的情况下声明。

function main() {
  console.log("Reading diplo data...\n\r");
  try {
    diplo_data = gameType(diplo);
    console.log(diplo_data);
  } catch (err) {
     return 'No game type!';
  }        
}