本文介紹了承諾,如何將變量傳遞給 .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 函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!