如果使用 Promise,我建议使用粗箭头函数,因为它打开了使用 this.foo 的可能性,即使在 .then 函数中也是如此
db.collection("cities").add({
name: "Tokyo",
country: "Japan"
})
.then(docRef => {
console.log("Document written with ID: ", docRef.id);
console.log("You can now also access this. as expected: ", this.foo)
})
.catch(error => console.error("Error adding document: ", error))
使用function(docRef)表示无法访问this.foo,会报错
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
console.log("You can now NOT access this. as expected: ", this.foo)
})
虽然粗箭头功能将允许您按预期访问this.foo
.then(docRef => {
console.log("Document written with ID: ", docRef.id);
console.log("You can now also access this. as expected: ", this.foo)
})
编辑/添加 2020:
如今,一种更流行的方式可能是使用 async/await 代替。请注意,您必须在函数声明前添加async:
async function addCity(newCity) {
const newCityAdded = await db.collection("cities").add(newCity)
console.log("the new city:", newCityAdded)
console.log("it's id:", newCityAdded.id)
}
如果您只想要 id,可以使用解构来获取它。解构允许您在响应中获取任何键/值对:
async function addCity(newCity) {
const { id } = await db.collection("cities").add(newCity)
console.log("the new city's id:", id)
}
也可以使用解构来获取值并重命名为您想要的任何内容:
async function addCity(newCity) {
const { id: newCityId } = await db.collection("cities").add(newCity)
console.log("the new city's id:", newCityId)
}