lon*_*gcc 0 javascript promise
Promise.resolve(123)
.then(String)
.then((data)=>{
console.log(data)
})
Run Code Online (Sandbox Code Playgroud)
这里运作正常.
但是,如果我将函数赋值给变量,并传递给Promise's .then().该函数只是忽略了我的回调.
例如,
Promise.resolve(123)
.then(String)
.then(myFunc)
var myFunc = (data)=>{
console.log(data)
}
Run Code Online (Sandbox Code Playgroud)
它不打印任何东西.唯一的区别是函数被赋值给一个变量,然后传递给.then(),而不是直接传递.但据我所知,应该没有区别.这是为什么?
(顺便说一句,我也试过了ES6之前的传统函数语法,但没有区别)
如注释中所示,使用分配给变量的函数不是问题.使用没有值的变量是一个问题.
唯一的区别是函数被赋值给一个变量,然后传递给.then(),而不是直接传递.
不,实际上,它被传递给.then() 然后分配给变量.有很大的不同.
在这个例子中,myFunc就是undefined当你使用它:
Promise.resolve(123)
.then(String)
.then(myFunc)
console.log('myFunc is', myFunc);
var myFunc = (data) => {
console.log(data)
}Run Code Online (Sandbox Code Playgroud)
解决方案:确保在使用之前myFunc具有值:
var myFunc = (data) => {
console.log(data)
}
Promise.resolve(123)
.then(String)
.then(myFunc)
console.log('myFunc is', myFunc);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |