Promise.resolve(123)
.then(String)
.then((data)=>{
console.log(data)
})
这里工作正常。
但是,如果我将函数分配给一个变量,并传递给 Promise 的 .then()
。该函数只是忽略我的回调。
例如,
Promise.resolve(123)
.then(String)
.then(myFunc)
var myFunc = (data)=>{
console.log(data)
}
它不打印任何内容。唯一的区别是函数被分配给一个变量然后传递给.then(),而不是直接传递。但据我所知,应该没有区别。这是为什么?
(顺便说一句,我也尝试了 ES6 之前的传统函数语法,但没有什么区别)
最佳答案
如注释中所示,使用分配给变量的函数不会出现问题。这是使用还没有值的变量的问题。
The only difference is that the function is assigned to a variable and then pass to the .then(), instead of passing directly.
不,实际上,它被传递给 .then()
然后分配给一个变量。差别很大。
在此示例中,myFunc
在使用时是未定义
:
Promise.resolve(123)
.then(String)
.then(myFunc)
console.log('myFunc is', myFunc);
var myFunc = (data) => {
console.log(data)
}
解决方案:确保 myFunc
在使用之前有一个值:
var myFunc = (data) => {
console.log(data)
}
Promise.resolve(123)
.then(String)
.then(myFunc)
console.log('myFunc is', myFunc);
关于javascript - Promise 的 .then() 不接受分配给变量的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51551826/