我有以下代码:
callAPI() {
return this.myModel.map(action(retValue => {
return this.myApi.doWork(retValue.Input).then(action(model => {
this.model.Input = Object.assign({}, model);
this.saveState();
})).catch(error => {
throw(error);
});
}));
如果我的客户端代码我这样做:
myStore.callAPI().then(() => {
console.log("completed");
this.setState({ loading: false });
});
我收到错误
.then()不是函数
我希望在所有异步操作完成后获得回调。
答案 0 :(得分:1)
请使用Promise.all
等待多个承诺并返回结果,这是另一个可以调用.then
的承诺。
为了在命令性代码块之后始终返回一个promise,您可以返回Promise.resolve()
,这将使代码可链接。
callAPI() {
return Promise.all(
this.myModel.map(action(retValue => (
this.myApi.doWork(retValue.Input).then(action(model => {
this.model.Input = Object.assign({}, model);
this.saveState();
return Promise.resolve();
}))
)));
);
}
请看一个例子:
const sleep = timeout => new Promise(resolve =>
setTimeout(() => resolve(timeout), timeout)
);
const tap = timeout => {
console.log(`Task completed after ${timeout}ms`);
return timeout;
}
const tasks = [
sleep(1000),
sleep(2000),
sleep(500),
sleep(30),
sleep(2500),
sleep(450)
].map(task => task.then(tap));
Promise.all(tasks).then(x => {
console.log(x);
});