本文介绍了类别中的Async/Await:意外的标记`this`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试异步/等待,我不明白为什么这行:
I am experimenting with async/await, I can't understand why this line :
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()
有人知道将异步方法的结果存储在变量中的正确语法吗?
Does anyone know the correct syntax to store the result of an async method in a variable?
谢谢.
推荐答案
为简单起见,它的发生是因为创建Promise时,在其构造函数中传递了一个箭头函数,该函数包含await
调用.您必须始终将async
关键字放在包含await
的函数的声明之前.
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
.
所以,不要这样做
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/article/understanding-javascript-async-await#using-async-await
这篇关于类别中的Async/Await:意外的标记`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!