我如何从javascript的承诺返回值?



我对承诺相当陌生,现在我被困住了。我读了一些文章和帖子,但我还是不明白。

我有一个简单的API,返回一个数组的人和一些属性,如姓,名和d.o.b.我想检查生日在未来10天内。现在我被返回一个承诺的函数困住了。我希望API返回一个数组,其中包含person数组和nextbirthday数组。

我如何解决这个承诺?

(我知道计算日期的部分不是最优雅的方式)

router.get('/', async(req, res) => {
try {
const contacts = await Contact.find()
// Returns promise, but want array
const nextBirthdays = getNextBirthdays(contacts)
var promise = Promise.resolve(nextBirthdays);
promise.then(function(val) {
console.log(val);
});
res.json({ contacts, nextBirthdays })

} catch (error) {
res.status(500).json({ message: error.message })
}
})
async function getNextBirthdays(contacts) {
contacts.forEach(async(contact) => {
let daysTillBirthday = await getDaysTillBirthday(contact.dob)
if (daysTillBirthday < 10 && daysTillBirthday > 0) {
console.log(`${contact.firstname}'s birthday is in ${daysTillBirthday} days`)
nextBirthdays.push({
firstname: contact.firstname,
days: daysTillBirthday
})
}
// Returns object with next birthdays
return nextBirthdays
})
}
async function getDaysTillBirthday(_birthday) {
const birthday = await birthdayDayOfYear(_birthday)
const today = await dayOfTheYear()
const days = birthday - today
return await days;
}
async function birthdayDayOfYear(date) {
const now = date;
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
return await day
}
async function dayOfTheYear() {
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
return await day
}

你的代码应该是这样的:

router.get('/', async (req, res) => {
try {
const contacts = await Contact.find()
const nextBirthdays = getNextBirthdays(contacts)
res.json({ contacts, nextBirthdays });
} catch (error) {
res.status(500).json({ message: error.message })
}
})
function getNextBirthdays(contacts) {
let nextBirthdays = [];
contacts.forEach(contact => {
let daysTillBirthday = getDaysTillBirthday(contact.dob)
if (daysTillBirthday < 10 && daysTillBirthday > 0) {
console.log(`${contact.firstname}'s birthday is in ${daysTillBirthday} days`)
nextBirthdays.push({
firstname: contact.firstname,
days: daysTillBirthday
})
}
})
// Returns object with next birthdays
return nextBirthdays
}
function getDaysTillBirthday(_birthday) {
const birthday = birthdayDayOfYear(_birthday);
const today = dayOfTheYear();
return birthday - today;
}
function birthdayDayOfYear(date) {
const now = date;
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
}
function dayOfTheYear() {
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
}
module.exports = router;

所有用于调用生日的实用程序函数都可以写成同步函数,因为您不需要"等待";对于一个结果,就像你对Contacts.find()做的那样;它们只是算术运算,可以立即返回。

虽然您可以将这些写成异步函数,但这是不必要的,因此只需从所有这些函数中删除所有async修饰符,然后在返回语句中删除所有await

然后在构建生日结果数组的forEach循环中删除async

所以要理解的关键是你的生日计算可以同步完成,所以根本不需要解决任何承诺。要理解如何解析承诺,可以将函数写成如下异步函数,以dayOfTheYear为例:

function dayOfTheYear() {
return new Promise((resolve) => {
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
resolve(day);      // this is you resolving the promise you return
});
}

如果要使用上面的函数,有两种不同的方法:

dayOfTheYear()
.then( (resolvedValue) => console.log(resolvedValue) )

resolvedValue是在调用resolve(day)时在函数中解析的内容。

或者不使用then函数来传递回调,您可以使用await:

// assuming this code is in a function declared as async
const resolvedValue = await dayOfTheYear();

因此,从上面可以看到,来自async函数的return语句与来自Promise回调的resolve调用做同样的事情。

最后一件事:从你的代码中可以明显看出,你对函数声明为async感到困惑。如果您将使用await来等待a Promise解析,则声明一个async函数。如果你不声明async,你就不能等待任何东西。但你永远只能等待承诺。

在底层,所有这些东西都是承诺,所有的承诺都只是回调。

希望这对你有帮助。

相关内容

  • 没有找到相关文章

最新更新