【发布时间】:2020-01-14 13:44:58
【问题描述】:
我有一个函数,它需要一个整数数组,然后它将调用另一个函数,该函数将接受一个整数并进行一些检查并返回一个承诺来解决它。
我知道 getDataById 函数并不依赖于执行异步工作,但我的这只是示例..
这是我的代码:
function getDataById(id) {
return new Promise((resolve, reject) => {
if (id > 0) resolve(id * 10);
if (id <= 0) reject("wrong input");
})
}
async function callService(idList) {
return await idList.map((id) => getDataById(id));
}
let teamIDList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1, -2, -3, -4];
callService(teamIDList).then(res => {
console.log(res);
});
我希望它会返回一个新数字数组和里面的一些字符串。 但它返回了一系列承诺。
【问题讨论】:
-
你不是
await-inggetDataById -
使用
Promise.all。此外,几乎不需要return await的东西。 -
因为 async 和 return await 做同样的事情来确保返回一个 promise?
-
@TianQin,不完全是。
async做了几件事,(1) 确保返回的任何内容都是 Promise 包装的,(2) 确保异步抛出错误,(3) 使await在函数中可用。没有强制在 AsyncFunction 中使用await。await仅在其后有语句或较大表达式的一部分时才有用。return await something()中的await是不必要的,因为return something()具有相同的净效应。
标签: javascript promise async-await