承诺,如何将变量传递给.then函数

Art*_*ero 6 javascript xmlhttprequest fetch promise

您好,这是一个帮助我了解Promise如何.then返回工作的问题. 问题是:如何将变量限定为第二个.然后链接函数?

这是一个jsbin http://jsbin.com/xacuna/edit?js,output

我可以访问全局变量,然后将范围变量传递给第一个变量,但不是之后.

  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}`)
})
Run Code Online (Sandbox Code Playgroud)

Jar*_*a X 5

当您使用 ES2015 时 - 简单的解决方案使用对象速记属性名称对象解构

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}`)
})
Run Code Online (Sandbox Code Playgroud)

  • 当然,当您可以使用 bind 使其过于复杂时,为什么要使用简单的更改 (3认同)