答应,如何将变量传递给.then函数

编程入门 行业动态 更新时间:2024-10-28 08:23:19
本文介绍了答应,如何将变量传递给.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 jsbin/xacuna/edit?js,output

Here is a jsbin jsbin/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('httpbin/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('httpbin/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函数

本文发布于:2023-11-23 18:13:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622414.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何将   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!