Returning await'd value in async function is returning a promise

后端 未结 1 1977
清歌不尽
清歌不尽 2021-01-23 09:05

In Javascript, I am trying to return an await\'d result from an async function. It seems if I use that result inside the async function then everything works fine, it gets treat

相关标签:
1条回答
  • 2021-01-23 09:42

    From async_function MDN :

    Return value

    A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.

    So putText() doesn't return the resolved value of retPromise() but returns a promise that will resolve with that value , so you have to use .then ( when fullfilled ) or .catch ( when rejected ) to access that.

    function retPromise() {
      return new Promise((resolve, reject) => resolve('Hello'));
    }
    
    async function putText() {
      let result = await retPromise();
      return result;
    }
    
    putText().then( result => $("#test").val(result) )
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
    <input type="text" id="test">

    0 讨论(0)
提交回复
热议问题