在异步函数中返回等待值正在返回一个承诺 [英] Returning await'd value in async function is returning a promise

查看:82
本文介绍了在异步函数中返回等待值正在返回一个承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我试图从异步函数返回等待结果.看来,如果我在async函数中使用该结果,则一切正常,它将被视为resolve()参数,一切都很好.但是,如果我尝试返回结果,即使有await语句,它也会被当作回调处理.

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 treated as the resolve() parameter and everything is fine and dandy. However if I try to return the result, it gets treated as a callback, even though the await statement is there.

例如(在异步函数中使用await'd结果): https://jsfiddle.net/w7n8f7m7/

For example (using await'd result inside the async func): https://jsfiddle.net/w7n8f7m7/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="test">

function retPromise() {
  return new Promise((resolve, reject) => resolve('Hello'));
}

async function putText() {
  let result = await retPromise();
  $("#test").val(result);
}

putText();

与返回值并在异步函数之外使用它相反: https://jsfiddle.net/hzoj2zyb/

versus returning the value and using it outside the async function: https://jsfiddle.net/hzoj2zyb/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="test">

function retPromise() {
  return new Promise((resolve, reject) => resolve('Hello'));
}

async function putText() {
  let result = await retPromise();
  return result;
}

$("#test").val(putText());

等待如何在第一个小提琴中正确返回已执行的诺言,而在第二个中却没有呢?是否因为jquery语句位于异步函数作用域内,所以才可以正确使用它?

How come the await is properly returning the executed promise in the first fiddle, but not in the second? Is it because the jquery statement is inside an async function scope, so then it is able to be used properly?

推荐答案

来自异步功能MDN :

返回值

一个Promise,它将由async函数返回的值解决,或者被async函数内部抛出的未捕获异常拒绝.

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.

因此,putText()不会返回retPromise()的已解析值,但会返回一个将使用该值解析的承诺,因此您必须使用.then(已满)或.catch(被拒绝)来访问它.

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">

这篇关于在异步函数中返回等待值正在返回一个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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