首页 > 解决方案 > nodejs - 试图从 async/await 函数中获取变量,但得到一个 promise 挂起错误

问题描述

这就是我所拥有的:

async function myFetch() {
    let loggerinfo = {
        url: await "Hellothere",
        token: await "212312"
    };

    return await loggerinfo;
  
  }
  
const myfish = myFetch().then((loggerinfo) => {
      return loggerinfo
  })

console.log(myfish);

当我输出 myfish 变量时,我得到一个“Promise { }”

我需要 async 和 await 属性,但同时,我需要能够使用 loggerinfo 变量,其中“myfish”要在 async 和 myFetch().then 框之外使用。

我的结果例如:

async function myFetch() {
    let loggerinfo = {
        url: await "Hellothere",
        token: await "212312"
    };

    return await loggerinfo;

  }

const myfish = myFetch().then((loggerinfo) => {
      return loggerinfo
  })

在exports.handler 中使用myfish

exports.handler = function (event, context) {
     console.log(myfish);
};

标签: node.jsaws-lambda

解决方案


async function myFetch() {
    let loggerinfo = {
       url: await "Hellothere",
       token: await "212312"
    };
    return loggerinfo;
}
const myfish = async () => {return await myFetch();}

使用上面的代码来获得您的预期结果。

在exports.handler 中使用myfish

exports.handler = async (event, context) {
 console.log(await myfish);
}

如上所述,您也可以在 lambda 函数中使用 async/await


推荐阅读