[英]Using await from function returning JSON in JavaScript
I have an async function that returns JSON:我有一个返回 JSON 的异步 function:
async function test() {
var answer = { "status": 0 };
return answer;
}
Case 1: Calling it using await when the function is called results the following output:情况 1:在调用 function 时使用 await 调用它会导致以下 output:
var test_k = await test();
console.log(test_k);
Output: { status: 0 }
Output: { status: 0 }
Case 2: Calling it using await later on the returned variable results the following output:情况 2:稍后在返回的变量上使用 await 调用它会产生以下 output:
var test_p = test();
await test_p;
console.log(test_p);
Output: Promise { { status: 0 } }
Output: Promise { { status: 0 } }
The output above are produced in Node.js v12.18.3
environment.上面的output是在Node.js v12.18.3
环境下制作的。
In Case 1, I can access test_k.status
.在案例 1 中,我可以访问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?我不能在案例2中做同样的事情。我需要访问案例2中的JSON object。我该怎么做?
Your case 2 code should read:您的案例 2 代码应为:
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.等待test_p
promise 不会更改 promise,它会将结果 output 分配给变量,因此您需要记录 output,而不仅仅是原始函数/承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.