如何等待异步.then
How to wait on async .then
这是我的代码:
let curId;
if (!user) {
db.collection("users")
.add({
name: name,
})
.then((doc) => curId = doc.id)
.catch((err) => console.error(err));
} else {
curId = user.id;
}
console.log(curId); <-- I need curId here
目前 curId
未定义,因为我没有等待异步代码完成 运行。实现此目标的最佳方法是什么?
我想到的一些方法:
- 使用
await
而不是 .then
但我觉得 organized/messy 与 try
和 catch
- 我也可以在
if
和 else
语句中添加我想用 curId
做的事情,但我不想写冗余代码
使用异步代码,您应该执行需要在 .then()
中等待结果的操作。有了这个,我看到了几个选项:
- 将其放入一个函数中,returns 承诺值
- 使用 curId 调用一个函数来执行您的逻辑
- 重组为单一承诺
选项 1
const getCurId = (user) => {
if (!user) {
return db.collection("users")
.add({ name: name })
.then((doc) => doc.id)
} else {
return Promise.resolve(user.id);
}
};
getCurId().then(curId => {
console.log(curId); // do things with curId here
}).catch((err) => console.error(err));
选项 2
if (!user) {
db.collection("users")
.add({ name: name })
.then((doc) => doc.id)
.then(doThingWithCurId)
.catch((err) => console.error(err));
} else {
doThingWithCurId(user.id);
}
const doThingWithCurId = (curId) => {
console.log(curId); // do things with curId here
};
选项 3
const curIdPromise = user ? Promise.resolve(user.id) : db.collection("users")
.add({ name: name })
.then((doc) => doc.id);
curIdPromise.then((curId) => {
console.log(curId); // do things with curId here
}).catch((err) => console.error(err));
这是我的代码:
let curId;
if (!user) {
db.collection("users")
.add({
name: name,
})
.then((doc) => curId = doc.id)
.catch((err) => console.error(err));
} else {
curId = user.id;
}
console.log(curId); <-- I need curId here
目前 curId
未定义,因为我没有等待异步代码完成 运行。实现此目标的最佳方法是什么?
我想到的一些方法:
- 使用
await
而不是.then
但我觉得 organized/messy 与try
和catch
- 我也可以在
if
和else
语句中添加我想用curId
做的事情,但我不想写冗余代码
使用异步代码,您应该执行需要在 .then()
中等待结果的操作。有了这个,我看到了几个选项:
- 将其放入一个函数中,returns 承诺值
- 使用 curId 调用一个函数来执行您的逻辑
- 重组为单一承诺
选项 1
const getCurId = (user) => {
if (!user) {
return db.collection("users")
.add({ name: name })
.then((doc) => doc.id)
} else {
return Promise.resolve(user.id);
}
};
getCurId().then(curId => {
console.log(curId); // do things with curId here
}).catch((err) => console.error(err));
选项 2
if (!user) {
db.collection("users")
.add({ name: name })
.then((doc) => doc.id)
.then(doThingWithCurId)
.catch((err) => console.error(err));
} else {
doThingWithCurId(user.id);
}
const doThingWithCurId = (curId) => {
console.log(curId); // do things with curId here
};
选项 3
const curIdPromise = user ? Promise.resolve(user.id) : db.collection("users")
.add({ name: name })
.then((doc) => doc.id);
curIdPromise.then((curId) => {
console.log(curId); // do things with curId here
}).catch((err) => console.error(err));