Donotalo
Donotalo

Reputation: 13025

Using await from function returning JSON in JavaScript

I have an async function that returns JSON:

async function test() {
    var answer = { "status": 0 };
    return answer;
}

Case 1: Calling it using await when the function is called results the following output:

var test_k = await test();
console.log(test_k);

Output: { status: 0 }

Case 2: Calling it using await later on the returned variable results the following output:

var test_p = test();

await test_p;
console.log(test_p);

Output: Promise { { status: 0 } }

The output above are produced in Node.js v12.18.3 environment.

In Case 1, I can access test_k.status. I can't do the same in Case 2. I need to access the JSON object in Case 2. How can I do that?

Upvotes: 0

Views: 52

Answers (1)

Luke Storry
Luke Storry

Reputation: 6722

Your case 2 code should read:

var test_p = test();

var output = await test_p;
console.log(output);

awaiting the test_p promise doesn't change that promise, it will output the result for you to then assign to a variable, so you need to log that output, not just the original function/promise.

Upvotes: 2

Related Questions