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

时间:2017-02-26 03:36:15

标签: javascript promise xmlhttprequest fetch

您好,这是一个帮助我了解Promises .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}`)
})

2 个答案:

答案 0 :(得分:2)

当您使用ES2015时 - 简易解决方案使用object Shorthand property namesObject 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}`)
})

答案 1 :(得分:0)

当我遇到这个答案时,我试图这样做:

for (key in updateDict)
{ if ( ! key.startsWith("__"))
  { var updateID        = updateDict[key].id;
    var updateNewValue  = updateDict[key].newValue;

    //store give the function call the ability to store the current value of key
    var storeAndDeleteKey = function(key, updateID, updateNewValue)
    { return atStore.update({"id":updateID}, updateNewValue))
        .then
        ( (docs) => 
          { results[key] = docs;
            delete updateDict[key];
          }
       );
    }

    //put the function with the current value of key into the Promise.all list
    dataAccessPromiseList.push
    ( storeAndDeleteKey(key, updateID, updateNewValue)
    )
  }
}

if (dataAccessPromiseList.length > 0) dataAccessPromise = Promise.all(dataAccessPromiseList);