是否有可能创建一个返回几个api调用的结果数组的函数?
而不是这样:
var func1;
var func2;
var func3;
apicall1().then((res) => {
func1 = res;
});
apicall1("string").then((res) => {
func2 = res;
});
apicall1(int).then((res) => {
func3 = res;
});
有这样的东西:
var result = [];
var Json = "{
"functions": [{
"name": "apicall1",
"args": null
}, {
"name": "apicall2",
"args": "string"
}, {
"name": "apicall2",
"args": [0, "string"]
}]
}";
MyFunction(Json) {
for (i = 0; i < functions.lenght; i += 1) {
functions[i].name(functions[i].args).then((res) => { result.push(res); });
}
return result;
}
我只是在寻找一些东西,以避免在另一个后面有一个X的愈伤组织。
谢谢;D
发布于 2018-03-19 09:03:58
可以使用Promise.all在数组中获得结果:
Promise.all([apicall1(), apicall1("string"), apicall1(int)])
.then(results => {
// Destructure the results into separate variables
let [func1, func2, func3] = results;
//access the results here
});发布于 2018-03-19 09:08:12
你应该用
Promise.all([ api1,api2,api2,...]).then(function(results){
}).catch(function(err){
})结果将是一个数组,其中包含相应索引中的所有响应。这里,您需要处理的一件事是异常。如果任何API调用发生在任何类型的异常中,它将被捕获。
发布于 2018-03-19 09:10:16
如果您想一个接一个地触发调用,可以使用async/await:
let result = [];
let funcs = [{
"name": "apicall1",
"args": null
}, {
"name": "apicall2",
"args": "string"
}, {
"name": "apicall2",
"args": [0, "string"]
}]
async makeCalls() {
for (let func of funcs) {
let res = await func.name(func.args)
result.push(res)
}
return result;
}
makeCalls()https://stackoverflow.com/questions/49359087
复制相似问题