首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用async/await获取SyntaxError

使用async/await获取SyntaxError
EN

Stack Overflow用户
提问于 2021-07-18 23:10:01
回答 1查看 35关注 0票数 0

我有以下代码,我正在尝试用node.js运行:

ethereum-block-by-date.js

代码语言:javascript
复制
module.exports = class {
    constructor(web3) {
        this.web3 = web3.constructor.name === 'Web3' ? web3 : { eth: web3 };
        this.checkedBlocks = {};
        this.savedBlocks = {};
        this.requests = 0;
    }
.
.
.
    async getEvery(duration, start, end, every = 1, after = true) {
        start = moment(start), end = moment(end);
        let current = start, dates = [];
        while (current.isSameOrBefore(end)) {
            dates.push(current.format());
            current.add(every, duration);
        }
        if (typeof this.firstBlock == 'undefined' || typeof this.latestBlock == 'undefined' || typeof this.blockTime == 'undefined') await this.getBoundaries();
        return await Promise.all(dates.map((date) => this.getDate(date, after)));
    }
.
.
.

getBlockNumber.js

代码语言:javascript
复制
const EthDater = require('ethereum-block-by-date');
const { ethers } = require('ethers');
const url = "node url";
const provider = new ethers.providers.WebSocketProvider(url);

const dater = new EthDater(
    provider
);

let blocks = await dater.getEvery('hours', '2018-11-15T00:00:00Z', '2018-11-22T00:00:00Z');

console.log(blocks);

当我运行node getBlockNumber.js时,我得到了引用let blocks = await dater.getEvery()函数调用的SyntaxError: await is only valid in async function

如果getEvery()ethereum-block-by-date.js中被定义为aync,那么它为什么要返回这个SyntaxError?当我从dater.getEvery()中删除await时,它会返回一个Promise对象。

EN

回答 1

Stack Overflow用户

发布于 2021-07-18 23:30:02

当我将await dater.getEvery()放在async函数中,然后调用该函数时,这个问题就解决了:

代码语言:javascript
复制
async function getBlocks() {
    let blocks = await dater.getEvery('hours', '2018-11-15T00:00:00Z', '2018-11-22T00:00:00Z');
    console.log(blocks);
}

getBlocks();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68430408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档