使用 async/await 未解决 Promise [英] Promise is not resolved using async/await

查看:42
本文介绍了使用 async/await 未解决 Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 async/await of promise 我已经创建了演示代码

I am trying to learn async/ await of promise I have created demo code

<html>
    <head>
        <script>
              async function getTested() {
              alert("line");
              let pp = await test1();
              alert(pp); //expected to print hello

              }

            async function test1 () {
                alert("line 9");
                let promise = await test2();
                alert(promise); //expected to print hello
                return promise;
            }

            function test2 () {
                alert("line 15");
                let promise = new Promise.resolve('hello');
                alert(promise);
                return promise;  
            }
        </script>
    </head>
    <body onload="getTested()"></body>
</html>

这里我使用 async/await 来解决我在 test1 和 getTested 中打印hello"的承诺.我在这里做什么错了?

Here I used async/await to resolve the promise I excepted it to print 'hello' in test1 and getTested. What is wrong I am doing here?

推荐答案

new Promise.resolve <- 有问题.

初始化并返回 Promise 对象.

Initialize and return the Promise object.

let promise = new Promise(function(r) {
    r("hello");
});

或者,您可以采用与您想采用的方法类似的方法:

Or, you can follow an approach similar as you wanted to follow:

Promise.resolve("hello"); 

async function getTested() {
  let pp = await test1();
  console.log(pp); //expected to print hello

}

async function test1() {
  let promise = await test2();
  console.log(promise); //expected to print hello
  return promise;
}

function test2() {
  return Promise.resolve("hello");
}

getTested()

这篇关于使用 async/await 未解决 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆