简体   繁体   English

如何在花括号内获取变量的值?

[英]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 我需要forEach之外的that.assigned的值,但是如果我将它用作console.log(that.assigned)这是一个数组,它将导致undefined

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 如果您使用的是ES 2017,则可以做到

(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. 否则,将无法使用回调。

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

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