2017-02-26 4 views
3

こんにちはこれは、約束が.thenの返品方法を理解するのを助けるための質問です。 質問は、どのようにして2番目のチェーン化された関数に変数をスコープできますか?ここで約束事、どのように変数を.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 o-chain-and-share-prior-results-with-promises/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

ありがとうございます。コールバックは1つの引数しか受け付けないので、その1つの引数をオブジェクトとしてラップします。私は気付いた。その後、コールバックにバインドすると、追加の引数を渡すことができます。 – ArturoRomero

+2

確かに、なぜ単純な変更を使用する場合は、バインドを使用してそれを過度に複雑にすることができます –

+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); 
関連する問題