gpt4 book ai didi

javascript - 类中的异步/等待 : unexpected token `this`

转载 作者:行者123 更新时间:2023-11-28 17:46:38 24 4
gpt4 key购买 nike

我正在尝试异步/等待,我不明白为什么这一行:

resolvedValue = await this.tryToSolve()

给我这个错误:

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

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

提前致谢。

最佳答案

为了简单起见,发生这种情况是因为当您创建 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

关于javascript - 类中的异步/等待 : unexpected token `this` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46565935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com