Promises, how to pass variable into .then function(承诺,如何将变量传递给 .then 函数)
问题描述
您好,这是一个帮助我了解 Promises .then
如何返回工作的问题.问题是:如何将变量范围限定为第二个 .then 链式函数?
Hello this is a question to help me understand how Promises .then
returns work. The question is: how can I scoped variables to the second .then chained function?
这是一个 jsbin http://jsbin.com/xacuna/edit?js,output
Here is a jsbin http://jsbin.com/xacuna/edit?js,output
我可以访问全局变量,然后将作用域变量传递给第一个,而不是之后.
I can access the global variables, and pass in the scoped variables to the first then, but not after.
let innerReturnFunction = (res, myName) => {
/* this works */
console.log(`hi from inner name: ${myName}`)
return res
}
let getInnerFuncVariable = () => {
var myName = 'arturo'
return fetch('https://httpbin.org/get')
.then(function (res) {
myName = 'Bob'
return innerReturnFunction(res, myName);
})
.then(function (res, myName) {
/* doesn't work, how can I access myName */
console.log(`in first then ${res.url}, ${myName}`)
});
}
getInnerFuncVariable().then(function(res, myName) {
/* how can I access myName */
console.log(`last called ${myName}`)
})
推荐答案
当你使用 ES2015 - 简单的解决方案使用 对象速记属性名称 和 对象解构
as you are using ES2015 - easy solution uses object Shorthand property names and Object destructuring
let innerReturnFunction = ({res, myName}) => {
/* this works */
console.log(`hi from inner name: ${myName}`);
return {res, myName}; // return an object
}
let getInnerFuncVariable = () => {
var myName = 'arturo';
return fetch('https://httpbin.org/get')
.then(function(res) {
myName = 'Bob'
return innerReturnFunction({res, myName});
})
.then(function({res, myName}) {
console.log(`in first then ${res.url}, ${myName}`);
return {res, myName};// ADD THIS!!
});
}
getInnerFuncVariable().then(function({res, myName}) {
console.log(`last called ${myName}`)
})
这篇关于承诺,如何将变量传递给 .then 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:承诺,如何将变量传递给 .then 函数


基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01