javascript - Promise 的 .then() 不接受分配给变量的函数?

标签 javascript promise

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/

相关文章:

javascript - 使用理想邮政编码查找时可能出现 jquery 冲突

javascript - jQuery Flexigrid 调整 IE7 中的列大小已损坏

javascript - 异步/等待错误处理

javascript - 尝试确定是否已加载所有图像时 Node.js 挂起

node.js - 在外面使用answer .then()并在node js中的另一部分代码中使用

javascript - 异步 promise 中未处理的 promise 拒绝

javascript - Jest 测试中 UnhandledPromiseRejectionWarning 的含义是什么?

javascript - 为什么 $ 在 jQuery 版本 1.4.2 中不被识别?

javascript - 如何通过 Javascript 或 JQuery 异步获取多个 JSON

asp.net - 在部分页面回发后选择 UpdatePanel 中 ASP.NET 文本框的内容