async/await 隐式返回承诺? [英] async/await implicitly returns promise?

查看:43
本文介绍了async/await 隐式返回承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到由 async 关键字标记的异步函数隐式返回一个承诺:

异步函数 getVal(){返回等待 doSomethingAync();}var ret = getVal();控制台日志(ret);

但这不是连贯的......假设 doSomethingAsync() 返回一个承诺,并且 await 关键字将从承诺中返回值,而不是承诺本身,然后我的 getVal 函数 应该返回那个值,而不是隐含的承诺.

那么究竟是怎么回事呢?由 async 关键字标记的函数是隐式返回 promise 还是我们控制它们返回的内容?

也许如果我们不显式返回某些东西,那么它们会隐式地返回一个承诺......?

说得更清楚,上面和

是有区别的

function doSomethingAync(charlie) {返回新的承诺(功能(解决){设置超时(函数(){解决(查理|| 'yikes');}, 100);})}异步函数 getVal(){var val = 等待 doSomethingAync();//val 不是承诺控制台日志(val);//记录 'yikes' 或其他什么返回值;//但这会返回一个承诺}var ret = getVal();控制台日志(ret);//记录一个承诺

在我的概要中,该行为确实与传统的 return 语句不一致.看起来,当您从 async 函数显式返回一个非承诺值时,它会强制将其包装在承诺中.我对它没有什么大问题,但它确实违反了普通的 JS.

解决方案

返回值将始终是一个 promise.如果你没有明确地返回一个promise,你返回的值会自动被包裹在一个promise中.

异步函数增量(num) {返回数字 + 1;}//即使你返回了一个数字,它的值也是//自动包装在一个 promise 中,所以我们调用//`then` 在它上面访问返回的值.////日志:4增量(3).then(num => console.log(num));

即使没有回报也一样!(Promise { undefined } 返回)

异步函数增量(num) {}

即使有 await 也是一样.

function defer(callback) {返回新的承诺(功能(解决){设置超时(功能(){解决(回调());}, 1000);});}异步函数 incrementTwice(num) {const numPlus1 = await defer(() => num + 1);返回 numPlus1 + 1;}//日志:5incrementTwice(3).then(num => console.log(num));

Promises 自动解包,因此如果您确实从 async 函数中返回一个值的承诺,您将收到该值的承诺(而不是该值的承诺的承诺).

function defer(callback) {返回新的承诺(功能(解决){设置超时(功能(){解决(回调());}, 1000);});}异步函数增量(数量){//这里是否放了一个 `await` 并不重要.return defer(() => num + 1);}//日志:4增量(3).then(num => console.log(num));


<块引用>

在我的概要中,行为确实与传统不一致返回语句.看来,当您明确返回一个来自异步函数的非承诺值,它将强制将其包装在一个承诺.我对它没有什么大问题,但它确实违反了正常JS.

ES6 的函数返回的值与 return 的值不同.这些函数称为生成器.

function* foo() {返回测试";}//记录一个对象.控制台日志(foo());//记录测试".console.log(foo().next().value);

I read that async functions marked by the async keyword implicitly return a promise:

async function getVal(){
 return await doSomethingAync();
}

var ret = getVal();
console.log(ret);

but that is not coherent...assuming doSomethingAsync() returns a promise, and the await keyword will return the value from the promise, not the promise itsef, then my getVal function should return that value, not an implicit promise.

So what exactly is the case? Do functions marked by the async keyword implicitly return promises or do we control what they return?

Perhaps if we don't explicitly return something, then they implicitly return a promise...?

To be more clear, there is a difference between the above and

function doSomethingAync(charlie) {
    return new Promise(function (resolve) {
        setTimeout(function () {
            resolve(charlie || 'yikes');
        }, 100);
    })
}

async function getVal(){
   var val = await doSomethingAync();  // val is not a promise
   console.log(val); // logs 'yikes' or whatever
   return val;  // but this returns a promise
}

var ret = getVal();
console.log(ret);  //logs a promise

In my synopsis the behavior is indeed inconsistent with traditional return statements. It appears that when you explicitly return a non-promise value from an async function, it will force wrap it in a promise. I don't have a big problem with it, but it does defy normal JS.

解决方案

The return value will always be a promise. If you don't explicitly return a promise, the value you return will automatically be wrapped in a promise.

async function increment(num) {
  return num + 1;
}

// Even though you returned a number, the value is
// automatically wrapped in a promise, so we call
// `then` on it to access the returned value.
//
// Logs: 4
increment(3).then(num => console.log(num));

Same thing even if there's no return! (Promise { undefined } is returned)

async function increment(num) {}

Same thing even if there's an await.

function defer(callback) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve(callback());
    }, 1000);
  });
}

async function incrementTwice(num) {
  const numPlus1 = await defer(() => num + 1);
  return numPlus1 + 1;
}

// Logs: 5
incrementTwice(3).then(num => console.log(num));

Promises auto-unwrap, so if you do return a promise for a value from within an async function, you will receive a promise for the value (not a promise for a promise for the value).

function defer(callback) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve(callback());
    }, 1000);
  });
}

async function increment(num) {
  // It doesn't matter whether you put an `await` here.
  return defer(() => num + 1);
}

// Logs: 4
increment(3).then(num => console.log(num));


In my synopsis the behavior is indeed inconsistent with traditional return statements. It appears that when you explicitly return a non-promise value from an async function, it will force wrap it in a promise. I don't have a big problem with it, but it does defy normal JS.

ES6 has functions which don't return exactly the same value as the return. These functions are called generators.

function* foo() {
  return 'test';
}

// Logs an object.
console.log(foo());

// Logs 'test'.
console.log(foo().next().value);

这篇关于async/await 隐式返回承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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