异步模块功能不起作用

时间:2019-09-27 20:00:11

标签: node.js

我是node.js的新手,正在遇到await / async函数的问题。这是我的文件:

main.js

var fd = require('fdmodule');
let r = await fd.matches();
console.log('r: ' + r);

fdmodule.js

const baseUrl = 'https://api.football-data.org/v2/';
const token = '*********';
const https = require('https');

exports.matches = async function () { 
    return new Promise(function (resolve, reject) {   
        let x = await callUrl(baseUrl + 'matches');
        console.log('x: ' + x);
        resolve(x);
    });
};

async function callUrl(url) {
    return new Promise(function (resolve, reject) {
        var req = require('request');
        var header = { headers: { 'X-Auth-Token': token } };
        req(url, header, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body);
            } else {
                reject(error);
            }
        });
    });
}

这是我的输出:

let r = await fd.matches();
        ^^^^^

SyntaxError: await is only valid in async function

当我删除此行的await并将函数更改为

exports.matches = function () {     
    let x = await callUrl(baseUrl + 'matches');
    console.log('x: ' + x);
    return x;    
};

我得到了console.log('x: ' + x);的结果,但是只有在console.log('r: ' + r);明显为空之后。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我整理了一下。这些是文件:

main.js

var fd = require('fdmodule');

loadMatches()

async function loadMatches() {    
    console.log('r: ' + await fd.matches());
}

fdmodule.js

const baseUrl = 'https://api.football-data.org/v2/';
const token = '*************';

exports.matches = async function () { 
    return await callUrl('matches');    
};

async function callUrl(url) {
    return new Promise(function (resolve, reject) {
        var req = require('request');
        var header = { headers: { 'X-Auth-Token': token } };
        req(baseUrl + url, header, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body);
            } else {
                reject(error);
            }
        });
    });
}