javascript - 如何从具有作为参数传递的本地值的函数返回新的承诺?
问题描述
我想返回 promise.all() 并在下面本地定义源变量,这样我就可以在调用 sourceRequest.then((sources)=>{//do something}) 时使用该承诺,这是我的代码:
var sourceRequest=(...countries)=>{
var sources=[];
var promisesCollection=[];
for(var country of countries)
{
var promise=this._vm.$axios.get('/sources',{params:{ country,language:'en'}})
.then(response=>{
sources.push(response.data.sources);
});
promisesCollection.push(promise);
}
Promise.all(promisesCollection).then(()=>{
return new Promise((resolve)=>resolve(sources));
})
};
sourceRequest('in').then((sources)=>console.log(sources));
问题是我在控制台中未定义 解决方法: 我有一个解决方法,但问题是我希望函数返回源而不是 api 请求响应:
//this works
var sourceRequest=(...countries)=>{
var promisesCollection=[];
for(var country of countries)
{
var promise=this._vm.$axios.get('/sources',{params:{ country,language:'en'}})
promisesCollection.push(promise);
}
return Promise.all(promisesCollection);
};
sourceRequest('in').then((response)=>{console.log(response)});
解决方案
然后,您只需要一个步骤,将响应列表替换为源列表。
const promisedSources = Promise.all(promisesCollection)
.then(responses =>
responses.map(response => response.data.sources)
);
return promisesSources;
推荐阅读
- eclipse - Javafx Stage 在显示元素前几秒钟是空白的
- powershell - 如何通过 powershell 代码提供键盘输入?
- opencv - 如何确定图像中的物体是平面还是非平面?
- node.js - 在 Node 服务器的 Mailgun 模板中使用变量
- firebase - 并发文档创建/删除时,firestore 事务是否会再次运行?
- angular-cli - Keycloak 应用程序中的 Service Worker 操作
- puppeteer - Target.sendMessageToTarget 已弃用——我现在如何使用 devtools 协议的扁平化风格?
- javascript - 循环形式的 AJAX 请求
- reactjs - Framer Motion:与父子动画冲突
- ajax - 使用ajax时如何获取数据表中列的所有数据