简体   繁体   English

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

[英]Promises, how to pass variable into .then function

Hello this is a question to help me understand how Promises .then returns work. 您好,这是一个帮助我了解Promises .then返还工作方式的问题。 The question is: how can I scoped variables to the second .then chained function? 问题是:如何将变量的作用域限定为第二个.then链接函数?

Here is a jsbin http://jsbin.com/xacuna/edit?js,output 这是一个jsbin http://jsbin.com/xacuna/edit?js,输出

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('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}`)
})

as you are using ES2015 - easy solution uses object Shorthand property names and Object destructuring 使用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}`)
})

When I came across this answer, I was trying to do this: 当我遇到这个答案时,我正在尝试这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM