0

So this is the code:

let pending_task_list = fetch("/tasks", {
    headers: {
        "Accept": "application/json"
    }
}).then(function(res) {
    return {succeeded: res.ok, pending_message: res.json()};
}).then(function(data){
    let message = data.pending_message;
    return {succeeded: data.succeeded, message: message};
});

...

let task_list = await pending_task_list;

Now, task_list.message is still a promise. How can resolve the promise given by res.json() in this case.

This question is different from Why does .json() return a promise? because I am looking for an answer on how to compose a value that has become available, with a value that is not yet available. While the particular application is to get json data back, the question covers a broader topic about promises and async functions in general.

user877329
  • 6,717
  • 8
  • 46
  • 88
  • "*This question is different from [Why does .json() return a promise?](https://stackoverflow.com/questions/37555031/why-does-json-return-a-promise)*" - I don't see how. The answer there does exactly what you are looking for. Even if you were asking the "*broader topic about promises and async functions in general*", [the canonical question on that](https://stackoverflow.com/q/28250680/1048572) was already linked there. – Bergi Jul 01 '23 at 13:19

1 Answers1

-1

edit your code like this

let pending_task_list = fetch("/tasks", {
    headers: {
        "Accept": "application/json"
    }
}).then(function(res) {
    return {succeeded: res.ok, pending_message: res.json()};
}).then(async function(data) {
    let message = await data.pending_message; // Await the promise resolution
    return {succeeded: data.succeeded, message: message};
});


let task_list = await pending_task_list;
Ramesh Kumar
  • 455
  • 3
  • 10
  • 1
    Don't mix `then` with `await` like this – Bergi Jun 21 '23 at 11:53
  • I am following users code pattern. not standerd but works. – Ramesh Kumar Jun 21 '23 at 11:59
  • @RameshKumar What would be the canonical answer then? – user877329 Jun 21 '23 at 12:13
  • 1
    @user877329 The canonical answer is to do something like shown in [the duplicate answer](https://stackoverflow.com/a/37555432/5648954). It does exactly what you're trying to do (composing the response and the data into one). Or, these days you can use `async`/`await` as another option without needing to call `.then()` at all. – Nick Parsons Jun 21 '23 at 12:17