NodeJS Async / Await - 使用 API 调用构建配置文件

NodeJS Async / Await - Build configuration file with API call

我想要一个配置文件,其中的变量设置了我从 API.

中获取的数据

我想我必须使用 asyncawait 功能来这样做,否则我的变量将保持未定义状态。

但我不知道如何集成它并使节点 exports.myVariable = myDataasync function 内可用?

下面是我尝试编写的代码(都在同一个文件中):

const fetchAPI = function(jsonQuery) {
    return new Promise(function (resolve, reject) {
        var reqOptions = {
            headers: apiHeaders,
            json:jsonQuery,
        }

        request.post(apiURL, function (error, res, body) {
            if (!error && res.statusCode == 200) {
                resolve(body);
            } else {
                reject(error);
            }
        });
    });
}
var wallsData = {}
const fetchWalls = async function (){

    var jsonQuery = [{ "recordType": "page","query": "pageTemplate = 1011"}]

    let body = await utils.fetchAPI(jsonQuery)

    let pageList = await body[0].dataHashes
    for(i=0;i<pageList.length;i++){
        var page = pageList[i]
        wallsData[page.title.fr] = [page.difficultyList,page.wallType]
    }
    return wallsData
    throw new Error("WOOPS")
}

try{

    const wallsData = fetchWalls()
    console.log(wallsData)
    exports.wallsData = wallsData

}catch(err){
    console.log(err)
}

console.log(wallsData) 的输出显示 Promise { <pending> },因此它没有被解析并且配置文件在没有 wallsData 中的数据的情况下继续执行...

我错过了什么?

谢谢, 干杯

你能改变这样的陈述吗,

try{

    const wallsData = fetchWalls();
    wallsData.then((result) => {
    console.log(result);
    });
    exports.wallsData = wallsData; // when importing in other file this returns as promise and we should use async/await to handle this.

}catch(err){


  console.log(err)
}

promise 是一种特殊的对象,它要么成功并返回结果,要么失败并被拒绝。 async-await-syntax 是帮助处理 promise 的语法糖。

如果您将一个函数定义为 aync,它总是将return一个承诺。

即使是这样的函数也读起来像

const foo = async() => {
     return "hello";
}

return是一个字符串的承诺,不仅仅是一个字符串。你需要等到它被解决或拒绝。

它类似于:

const foo = async() => {
     return Promise.resolve("Hello");
}

或:

const foo = async() => {
     return new Promise(resolve => resolve("Hello"));
}

您的 fetchWalls 同样是一个将在一段时间内保持未决状态的承诺。您必须通过在外部范围中设置 thencatch 处理程序来确保它成功或失败:

fetchWalls()
    .then(console.log)
    .catch(console.error);

外部作用域永远不会异步,因此您不能在那里使用 await。您只能在其他异步函数中使用 await。

我也不会将您的 try-catch 用于外部范围承诺处理。我认为您混淆了打算在 异步函数中使用的 try-catch 方法,因为它有助于避免嵌套和读取同步代码:

例如你可以在你的 fetchWalls 定义中做:

const fetchWalls = async function (){
    var jsonQuery = [{ "recordType": "page","query": "pageTemplate = 1011"}]

    try {
        let body = await utils.fetchAPI(jsonQuery)
    } catch(e) {
         // e is the reason of the promise rejection if you want to decide what to do based on it. If you would not catch it, the rejection would chain through to the first error handler.
    }

    ...
}