如何在使用promise一段时间后从对象中获取值



我正在获取一个事件的用户对象。如果我安慰用户_properties.uid在setTimeout之前,我得到了未定义的值。但如果我使用超时,我就会得到值。这意味着几秒钟后我们就会得到uid。

如何不使用超时或间隔获取uid?

room.on(
window.JitsiMeetJS.events.conference.USER_JOINED,
(id: any, user: any) => {
console.log(
`user joined - ${id} ${user.getDisplayName()}`,
user,
user._displayName,
);
const userName = user.getDisplayName();
if (userName) {
setTimeout(() => {
// new joining user id
const newUserId = user?._properties?.uid;
const index = participantsInRoom.findIndex(
(element: any) => element?._properties?.uid === newUserId,
);
if (index === -1) {
toaster('userjoined', userName);
}
}, 600);
}
setRemoteUsers(id);
if (userName) {
setRemoteName(id, userName);
}
},
);

如果你使用promise,你可以这样调用promise的then函数:

return new Promise((resolve, reject) => {
//do somthing
//call resolve if complete with any data you want to return
resolve(data);
// or call reject when error
// reject can pass data or not
reject();
}).then((data) => {
// this data is data you pass in resolve function
// do somthing ex: const newUserId = data?._properties?.uid;
}

您可以编写这样的函数来获得用户返回承诺:

function getUser() {
return new Promise((resolve, reject) => {
//do somthing
/call resolve if complete with any data you want to return
resolve(data);
// or call reject when error
// reject can pass data or not
reject();
});
}

当你处理你的用户时,你可以调用:

this.getUser().then((data) => {
// this data is data you pass in resolve function
// do somthing ex: const newUserId = data?._properties?.uid;
}

希望得到帮助!

最新更新