Create a Promise<Map> from several Promise
I am trying to get the bills for a number of customers, using typescript:
I have a Server class, handling the queries to the server, and providing a getBills
class, which returns a Promise<Bill>
:
class Server {
constructor(hostname?: string) {
hostname = hostname || "";
}
getBills(customer: Customer): Promise<Datapoint> {
const apiEndPoint = new URL("/API/Bills");
let parameters = { customer: customer.name};
//Fetch official doc
//https://github.com/whatwg/fetch/issues/56
Object.keys(parameters).forEach(key => apiEndPoint.searchParams.append(key, parameters[key]));
return fetch(apiEndPoint.toString())
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
}
}
I would like to query the bills for several customers, and return a Map for further processing (and to keep it all async, a Promise<Map<Customer, Bill>>
, but I am struggling with this step.
What I have so far:
getBills(): Promise<Map<Customer, Bill>> {
let server = this.context.server;
let resultMap = new Map<Customer, Bill>();
let promises = ;
for (let customer of this.customers) {
promises.push(
server.getBills(customer).then(result => resultMap.set(customer, result))
);
}
Promise.all(promises).then(return resultMap);
}
But it does not compile, since it is trying to return the map itself, and not a Promise.
I have tried to use
Promise.all(promises).then(return Promise.resolve(resultMap));
but is does not work either.
Could you point me in the right direction?
typescript promise
add a comment |
I am trying to get the bills for a number of customers, using typescript:
I have a Server class, handling the queries to the server, and providing a getBills
class, which returns a Promise<Bill>
:
class Server {
constructor(hostname?: string) {
hostname = hostname || "";
}
getBills(customer: Customer): Promise<Datapoint> {
const apiEndPoint = new URL("/API/Bills");
let parameters = { customer: customer.name};
//Fetch official doc
//https://github.com/whatwg/fetch/issues/56
Object.keys(parameters).forEach(key => apiEndPoint.searchParams.append(key, parameters[key]));
return fetch(apiEndPoint.toString())
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
}
}
I would like to query the bills for several customers, and return a Map for further processing (and to keep it all async, a Promise<Map<Customer, Bill>>
, but I am struggling with this step.
What I have so far:
getBills(): Promise<Map<Customer, Bill>> {
let server = this.context.server;
let resultMap = new Map<Customer, Bill>();
let promises = ;
for (let customer of this.customers) {
promises.push(
server.getBills(customer).then(result => resultMap.set(customer, result))
);
}
Promise.all(promises).then(return resultMap);
}
But it does not compile, since it is trying to return the map itself, and not a Promise.
I have tried to use
Promise.all(promises).then(return Promise.resolve(resultMap));
but is does not work either.
Could you point me in the right direction?
typescript promise
add a comment |
I am trying to get the bills for a number of customers, using typescript:
I have a Server class, handling the queries to the server, and providing a getBills
class, which returns a Promise<Bill>
:
class Server {
constructor(hostname?: string) {
hostname = hostname || "";
}
getBills(customer: Customer): Promise<Datapoint> {
const apiEndPoint = new URL("/API/Bills");
let parameters = { customer: customer.name};
//Fetch official doc
//https://github.com/whatwg/fetch/issues/56
Object.keys(parameters).forEach(key => apiEndPoint.searchParams.append(key, parameters[key]));
return fetch(apiEndPoint.toString())
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
}
}
I would like to query the bills for several customers, and return a Map for further processing (and to keep it all async, a Promise<Map<Customer, Bill>>
, but I am struggling with this step.
What I have so far:
getBills(): Promise<Map<Customer, Bill>> {
let server = this.context.server;
let resultMap = new Map<Customer, Bill>();
let promises = ;
for (let customer of this.customers) {
promises.push(
server.getBills(customer).then(result => resultMap.set(customer, result))
);
}
Promise.all(promises).then(return resultMap);
}
But it does not compile, since it is trying to return the map itself, and not a Promise.
I have tried to use
Promise.all(promises).then(return Promise.resolve(resultMap));
but is does not work either.
Could you point me in the right direction?
typescript promise
I am trying to get the bills for a number of customers, using typescript:
I have a Server class, handling the queries to the server, and providing a getBills
class, which returns a Promise<Bill>
:
class Server {
constructor(hostname?: string) {
hostname = hostname || "";
}
getBills(customer: Customer): Promise<Datapoint> {
const apiEndPoint = new URL("/API/Bills");
let parameters = { customer: customer.name};
//Fetch official doc
//https://github.com/whatwg/fetch/issues/56
Object.keys(parameters).forEach(key => apiEndPoint.searchParams.append(key, parameters[key]));
return fetch(apiEndPoint.toString())
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
}
}
I would like to query the bills for several customers, and return a Map for further processing (and to keep it all async, a Promise<Map<Customer, Bill>>
, but I am struggling with this step.
What I have so far:
getBills(): Promise<Map<Customer, Bill>> {
let server = this.context.server;
let resultMap = new Map<Customer, Bill>();
let promises = ;
for (let customer of this.customers) {
promises.push(
server.getBills(customer).then(result => resultMap.set(customer, result))
);
}
Promise.all(promises).then(return resultMap);
}
But it does not compile, since it is trying to return the map itself, and not a Promise.
I have tried to use
Promise.all(promises).then(return Promise.resolve(resultMap));
but is does not work either.
Could you point me in the right direction?
typescript promise
typescript promise
asked Jan 2 at 10:59
MaximeMaxime
570415
570415
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
It is a syntax error to write:
.then(return resultMap);
The then
method must receive a function as argument, while return
is just a statement, not a function. So change to:
.then(() => resultMap);
add a comment |
@trincot already explained the syntax error, but instead of just writing return Promise.all(promises).then(() => { return resultMap; });
I would suggest not constructing the Map
until you have all the results:
getBills(): Promise<Map<Customer, Bill>> {
const server = this.context.server;
const promises = this.customers.map(customer =>
server.getBills(customer).then(bills => [customer, bills])
);
return Promise.all(promises).then(tuples => new Map(tuples));
}
Thank you for the suggestion, but I have trouble getting it to work. Indeed, as is,promises
is a nested array, with typePromise<(Customer | Bill)>
I guess I would need to flatten this array, but doing this while keeping type safety seems more tedious than doing nothing :)
– Maxime
Jan 2 at 16:01
@Maxime the type interference can't know, but what I meant wasPromise<[Customer, Bill]>
. UsingPromise.all
on that gives us aPromise<[Customer, Bill]>
where we have an array of tuples (not an array of arrays ofCumstomer
s orBill
s), which is exactly what theMap
constructor expects.
– Bergi
Jan 2 at 19:16
1
thank you for the explanation. The solution was to explicitely type the tuple:const promises = this.customers.map(customer => server.getBills(customer).then(bills => { return <[Customer, Bills]>[customer, bills]}))
– Maxime
Jan 3 at 7:59
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54005118%2fcreate-a-promisemapt-u-from-several-promiseu%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
It is a syntax error to write:
.then(return resultMap);
The then
method must receive a function as argument, while return
is just a statement, not a function. So change to:
.then(() => resultMap);
add a comment |
It is a syntax error to write:
.then(return resultMap);
The then
method must receive a function as argument, while return
is just a statement, not a function. So change to:
.then(() => resultMap);
add a comment |
It is a syntax error to write:
.then(return resultMap);
The then
method must receive a function as argument, while return
is just a statement, not a function. So change to:
.then(() => resultMap);
It is a syntax error to write:
.then(return resultMap);
The then
method must receive a function as argument, while return
is just a statement, not a function. So change to:
.then(() => resultMap);
answered Jan 2 at 11:10


trincottrincot
129k1689123
129k1689123
add a comment |
add a comment |
@trincot already explained the syntax error, but instead of just writing return Promise.all(promises).then(() => { return resultMap; });
I would suggest not constructing the Map
until you have all the results:
getBills(): Promise<Map<Customer, Bill>> {
const server = this.context.server;
const promises = this.customers.map(customer =>
server.getBills(customer).then(bills => [customer, bills])
);
return Promise.all(promises).then(tuples => new Map(tuples));
}
Thank you for the suggestion, but I have trouble getting it to work. Indeed, as is,promises
is a nested array, with typePromise<(Customer | Bill)>
I guess I would need to flatten this array, but doing this while keeping type safety seems more tedious than doing nothing :)
– Maxime
Jan 2 at 16:01
@Maxime the type interference can't know, but what I meant wasPromise<[Customer, Bill]>
. UsingPromise.all
on that gives us aPromise<[Customer, Bill]>
where we have an array of tuples (not an array of arrays ofCumstomer
s orBill
s), which is exactly what theMap
constructor expects.
– Bergi
Jan 2 at 19:16
1
thank you for the explanation. The solution was to explicitely type the tuple:const promises = this.customers.map(customer => server.getBills(customer).then(bills => { return <[Customer, Bills]>[customer, bills]}))
– Maxime
Jan 3 at 7:59
add a comment |
@trincot already explained the syntax error, but instead of just writing return Promise.all(promises).then(() => { return resultMap; });
I would suggest not constructing the Map
until you have all the results:
getBills(): Promise<Map<Customer, Bill>> {
const server = this.context.server;
const promises = this.customers.map(customer =>
server.getBills(customer).then(bills => [customer, bills])
);
return Promise.all(promises).then(tuples => new Map(tuples));
}
Thank you for the suggestion, but I have trouble getting it to work. Indeed, as is,promises
is a nested array, with typePromise<(Customer | Bill)>
I guess I would need to flatten this array, but doing this while keeping type safety seems more tedious than doing nothing :)
– Maxime
Jan 2 at 16:01
@Maxime the type interference can't know, but what I meant wasPromise<[Customer, Bill]>
. UsingPromise.all
on that gives us aPromise<[Customer, Bill]>
where we have an array of tuples (not an array of arrays ofCumstomer
s orBill
s), which is exactly what theMap
constructor expects.
– Bergi
Jan 2 at 19:16
1
thank you for the explanation. The solution was to explicitely type the tuple:const promises = this.customers.map(customer => server.getBills(customer).then(bills => { return <[Customer, Bills]>[customer, bills]}))
– Maxime
Jan 3 at 7:59
add a comment |
@trincot already explained the syntax error, but instead of just writing return Promise.all(promises).then(() => { return resultMap; });
I would suggest not constructing the Map
until you have all the results:
getBills(): Promise<Map<Customer, Bill>> {
const server = this.context.server;
const promises = this.customers.map(customer =>
server.getBills(customer).then(bills => [customer, bills])
);
return Promise.all(promises).then(tuples => new Map(tuples));
}
@trincot already explained the syntax error, but instead of just writing return Promise.all(promises).then(() => { return resultMap; });
I would suggest not constructing the Map
until you have all the results:
getBills(): Promise<Map<Customer, Bill>> {
const server = this.context.server;
const promises = this.customers.map(customer =>
server.getBills(customer).then(bills => [customer, bills])
);
return Promise.all(promises).then(tuples => new Map(tuples));
}
answered Jan 2 at 12:07
BergiBergi
378k63577908
378k63577908
Thank you for the suggestion, but I have trouble getting it to work. Indeed, as is,promises
is a nested array, with typePromise<(Customer | Bill)>
I guess I would need to flatten this array, but doing this while keeping type safety seems more tedious than doing nothing :)
– Maxime
Jan 2 at 16:01
@Maxime the type interference can't know, but what I meant wasPromise<[Customer, Bill]>
. UsingPromise.all
on that gives us aPromise<[Customer, Bill]>
where we have an array of tuples (not an array of arrays ofCumstomer
s orBill
s), which is exactly what theMap
constructor expects.
– Bergi
Jan 2 at 19:16
1
thank you for the explanation. The solution was to explicitely type the tuple:const promises = this.customers.map(customer => server.getBills(customer).then(bills => { return <[Customer, Bills]>[customer, bills]}))
– Maxime
Jan 3 at 7:59
add a comment |
Thank you for the suggestion, but I have trouble getting it to work. Indeed, as is,promises
is a nested array, with typePromise<(Customer | Bill)>
I guess I would need to flatten this array, but doing this while keeping type safety seems more tedious than doing nothing :)
– Maxime
Jan 2 at 16:01
@Maxime the type interference can't know, but what I meant wasPromise<[Customer, Bill]>
. UsingPromise.all
on that gives us aPromise<[Customer, Bill]>
where we have an array of tuples (not an array of arrays ofCumstomer
s orBill
s), which is exactly what theMap
constructor expects.
– Bergi
Jan 2 at 19:16
1
thank you for the explanation. The solution was to explicitely type the tuple:const promises = this.customers.map(customer => server.getBills(customer).then(bills => { return <[Customer, Bills]>[customer, bills]}))
– Maxime
Jan 3 at 7:59
Thank you for the suggestion, but I have trouble getting it to work. Indeed, as is,
promises
is a nested array, with type Promise<(Customer | Bill)>
I guess I would need to flatten this array, but doing this while keeping type safety seems more tedious than doing nothing :)– Maxime
Jan 2 at 16:01
Thank you for the suggestion, but I have trouble getting it to work. Indeed, as is,
promises
is a nested array, with type Promise<(Customer | Bill)>
I guess I would need to flatten this array, but doing this while keeping type safety seems more tedious than doing nothing :)– Maxime
Jan 2 at 16:01
@Maxime the type interference can't know, but what I meant was
Promise<[Customer, Bill]>
. Using Promise.all
on that gives us a Promise<[Customer, Bill]>
where we have an array of tuples (not an array of arrays of Cumstomer
s or Bill
s), which is exactly what the Map
constructor expects.– Bergi
Jan 2 at 19:16
@Maxime the type interference can't know, but what I meant was
Promise<[Customer, Bill]>
. Using Promise.all
on that gives us a Promise<[Customer, Bill]>
where we have an array of tuples (not an array of arrays of Cumstomer
s or Bill
s), which is exactly what the Map
constructor expects.– Bergi
Jan 2 at 19:16
1
1
thank you for the explanation. The solution was to explicitely type the tuple:
const promises = this.customers.map(customer => server.getBills(customer).then(bills => { return <[Customer, Bills]>[customer, bills]}))
– Maxime
Jan 3 at 7:59
thank you for the explanation. The solution was to explicitely type the tuple:
const promises = this.customers.map(customer => server.getBills(customer).then(bills => { return <[Customer, Bills]>[customer, bills]}))
– Maxime
Jan 3 at 7:59
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54005118%2fcreate-a-promisemapt-u-from-several-promiseu%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown