Async/Await in a Class : unexpected token `this`

2019-08-22 02:44发布

I am experimenting with async/await, I can't understand why this line :

resolvedValue = await this.tryToSolve()

gives me this error :

Unexpected token this

class Test {

	constructor() {
		this.method = 0
		this.checkLink()
	}

	async checkLink() {
		return new Promise((resolve, reject) => {

			let resolvedValue

			for (let i = 0; i < 3; i++) {
				this.method = i
				resolvedValue = await this.tryToSolve()
				if (resolvedValue) break
			}
			console.log(`Method ${this.method} did the trick.`);
			resolve(resolvedValue)
		})
	}

	tryToSolve() {
		return new Promise((resolve, reject) => { // Resolves if this.method==1
			console.log(`Trying to solve with method ${this.method}...`);
			setTimeout(() => {
				resolve(!!this.method ? `http://www${this.method}.someurl.com` : false)
			}, 1000)
		})
	}
}

const test = new Test()

Does anyone know the correct syntax to store the result of an async method in a variable?

Thanks in advance.

2条回答
时光不老,我们不散
2楼-- · 2019-08-22 03:14

Drop the new Promise around the await! You want only

async checkLink() {
    let resolvedValue
    for (let i = 0; i < 3; i++) {
        this.method = i
        resolvedValue = await this.tryToSolve()
        if (resolvedValue) break
    }
    console.log(`Method ${this.method} did the trick.`);
    return resolvedValue;
}

or much simpler

async checkLink() {
    for (let i = 0; i < 3; i++) {
        const value = await this.tryToSolve()
        if (value) {
            console.log(`Method ${i} did the trick.`);
            return value;
        }
    }
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-22 03:17

To keep things simple, it happens because when you create a Promise, in its' constructor you pass an arrow function, which contains await call. You must always put async keyword before the declaration of a function, that contains await.

So, instead of doing this

async checkLink() {
    return new Promise((resolve, reject) => {

        let resolvedValue

        for (let i = 0; i < 3; i++) {
            this.method = i
            resolvedValue = await this.tryToSolve()
            if (resolvedValue) break
        }
        console.log(`Method ${this.method} did the trick.`);
        resolve(resolvedValue)
    })
}

Do it like this

checkLink() {
    return new Promise(async (resolve, reject) => {

        let resolvedValue

        for (let i = 0; i < 3; i++) {
            this.method = i
            resolvedValue = await this.tryToSolve()
            if (resolvedValue) break
        }
        console.log(`Method ${this.method} did the trick.`);
        resolve(resolvedValue)
    })
}

More info: https://ponyfoo.com/articles/understanding-javascript-async-await#using-async-await

查看更多
登录 后发表回答