2017-02-26 103 views
3

您好,这是一个问题,可以帮助我理解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}`) 
}) 
+1

在随后的回调只接受一个参数 - 一个“对象”会很有用 –

+1

请参阅[链接承诺时如何共享先前的结果](http://stackoverflow.com/questions/28714298/how-t邻链和股的在先结果与 - 承诺/ 28714863#28714863)。 – jfriend00

回答

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}`) 
}) 
+0

谢谢你的回应。在那里的回调只接受一个参数,所以把这个参数作为一个对象包装起来。我注意到。在回调函数上绑定允许你传递额外的参数。 – ArturoRomero

+2

当然,为什么使用一个简单的更改,当你可以使用bind过度复杂 –

+0

你是对的,绑定使代码看起来更复杂一点。 – ArturoRomero

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);