Node.js NodeJS Async/Await-使用API调用生成配置文件

Node.js NodeJS Async/Await-使用API调用生成配置文件,node.js,async-await,configuration-files,Node.js,Async Await,Configuration Files,我希望有一个配置文件,其中的变量设置为我从API获取的数据 我想我必须使用async和wait特性来实现这一点,否则我的变量将保持未定义状态 但是我不知道如何集成它并在异步函数中保持节点exports.myVariable=myData可用 下面是我试图编写的代码(都在同一个文件中): const fetchAPI=function(jsonQuery){ 返回新承诺(功能(解决、拒绝){ var reqOptions={ 标题:ApiHeader, json:jsonQuery, } post

我希望有一个配置文件,其中的变量设置为我从API获取的数据

我想我必须使用
async
wait
特性来实现这一点,否则我的变量将保持未定义状态

但是我不知道如何集成它并在
异步函数中保持节点
exports.myVariable=myData
可用

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

const fetchAPI=function(jsonQuery){
返回新承诺(功能(解决、拒绝){
var reqOptions={
标题:ApiHeader,
json:jsonQuery,
}
post(apirl,函数(error,res,body){
如果(!error&&res.statusCode==200){
决议(机构);
}否则{
拒绝(错误);
}
});
});
}
var wallsData={}
const fetchWalls=异步函数(){
var jsonQuery=[{“recordType”:“page”,“query”:“pageTemplate=1011”}]
let body=await utils.fetchAPI(jsonQuery)
让pageList=等待正文[0]。数据哈希

对于(i=0;i你能改变如下语句吗

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 Wait语法是帮助处理promise的语法糖

如果将函数定义为aync,它将始终返回承诺

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

const foo = async() => {
     return "hello";
}
返回字符串的承诺,而不仅仅是字符串。您需要等待它被解析或拒绝

它类似于:

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

您的
fetchWalls
同样是一个承诺,将在一段时间内保持挂起状态。您必须通过在外部作用域中设置
然后
捕获
处理程序来确保它成功或失败:

fetchWalls()
    .then(console.log)
    .catch(console.error);
外部作用域从不异步,因此不能在那里使用wait。只能在其他异步函数中使用wait

我也不会将您的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.
    }

    ...
}

您必须等待
fetchWalls()
cause是一个异步函数,因此promise基本上您应该导出
fetchWalls
,而不是最终值。当您需要此函数时,它会立即从另一个模块开始执行。更好的做法是需要该模块,然后手动管理fetchWalls函数。我非常怀疑您的
正文[0].dataHashes
是一个承诺,因此您无需等待。感谢您的精确回答,它帮助我理解了承诺和异步函数的概念。我遵循了您的提示,并使其工作正常!
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.
    }

    ...
}