如何解决等待正确的承诺?

How to solve promise with await correct?

有人能告诉我为什么 await 不在这里工作吗?

const Web3 = require('web3');

web3 = new Web3(new Web3.providers.HttpProvider("http://<ip>:8545"));

let accounts = (async () => await web3.eth.getAccounts())();

// await was not working, here I get a promise
console.log(accounts);

// if I wait with a timeout I get my accounts
setTimeout(() => console.log(accounts), 5000);

您的 console.log 必须在内联异步函数中。

(async () => {
   accounts = await web3.eth.getAccounts()
   console.log(accounts);
}
)();

不是这样的。一个异步函数 returns 一个承诺。 console.log 外部异步函数不会等待 await。您只能在异步函数中停止代码。

async function getData() {
    const answer = await web3.eth.getAccounts()
    console.log(answer) /* this console.log will be wait */
    return answer
}

getData().then(answer => console.log(answer))

如果它像那样工作(将代码保存在函数之外),它将停止浏览器上的所有进程(如警报功能)并且用户也必须等待。