在类中异步/等待:意外令牌`this`

时间:2017-10-04 13:18:22

标签: javascript class async-await

我正在尝试async / await,我无法理解为什么这一行:

resolvedValue = await this.tryToSolve()

给了我这个错误:

  

意外的令牌



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()
&#13;
&#13;
&#13;

有没有人知道将异步方法的结果存储在变量中的正确语法?

提前致谢。

2 个答案:

答案 0 :(得分:2)

为了简单起见,它会发生,因为当你创建一个Promise时,它会在其中发生。构造函数,您传递一个箭头函数,其中包含await调用。您必须始终在函数声明之前放置async关键字,该函数包含await

所以,而不是这样做

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)
    })
}

这样做

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)
    })
}

更多信息:https://ponyfoo.com/articles/understanding-javascript-async-await#using-async-await

答案 1 :(得分:1)

放弃new Promise around the await!你只想要

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;
}

或更简单

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;
        }
    }
}