简体   繁体   中英

How to take the value of a variable inside the curly braces?

I need the value of that.assigned outside the forEach but it would result with undefined if I ever use it as console.log(that.assigned) which is an array

assignedDoctors.then(function(doc){
  let i = 0;
  doc.forEach(function(md){
    tmpMDs.push(md.data());
    tmpMDs[i].key = md.id;
    // tmpMDs.push(md.data().push());
    i++;
  });
  that.assigned = tmpMDs;
}).catch(function(e){
  console.log(e);
});

console.log(that.assigned)

namedDoctors.then是一个promise函数,您不能在调用promise函数之前访问该变量的值。

If you are using ES 2017, then you can do it

(async function(){

that.assigned = await assignedDoctors.then(function(doc){
  let i = 0;
  doc.forEach(function(md){
    tmpMDs.push(md.data());
    tmpMDs[i].key = md.id;
    // tmpMDs.push(md.data().push());
    i++;
  });

  return tmpMDs;
});

})()

Otherwise, no way to use the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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