我正在尝试异步/等待,我不明白为什么这行:
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()
有人知道正确的语法将异步方法的结果存储在变量中吗?
预先感谢。
要使事情变得简单,它发生了,因为当您创建诺言时,在其'构造函数中,您通过箭头函数,其中包含 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
在 await
周围丢下 new Promise
!您只需要
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;
}
}
}