問(wèn)題描述
您好,這是一個(gè)幫助我了解 Promises .then
如何返回工作的問(wèn)題.問(wèn)題是:如何將變量范圍限定為第二個(gè) .then 鏈?zhǔn)胶瘮?shù)?
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?
這是一個(gè) jsbin http://jsbin.com/xacuna/edit?js,output
Here is a jsbin http://jsbin.com/xacuna/edit?js,output
我可以訪問(wèn)全局變量,然后將作用域變量傳遞給第一個(gè),而不是之后.
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}`)
})
推薦答案
當(dāng)你使用 ES2015 - 簡(jiǎn)單的解決方案使用 對(duì)象速記屬性名稱(chēng) 和 對(duì)象解構(gòu)
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}`)
})
這篇關(guān)于承諾,如何將變量傳遞給 .then 函數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!