您好,这是一个帮助我理解 Promise 的问题.then
返回工作。问题是:如何将变量的作用域限定为第二个 .then 链函数?
这是一个jsbinhttp://jsbin.com/xacuna/edit?js,输出
我可以访问全局变量,并将作用域变量传递给第一个 then,但不能传递给后面的变量。
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 时 - 简单的解决方案使用object 属性名称简写 and 对象解构
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}`)
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)