异步/等待隐含返回承诺? [英] async/await implicitly returns promise?

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

问题描述

我读了由异步标记关键字异步函数隐含返回一个承诺:

 异步功能GETVAL(){
 返回等待doSomethingAync();
}VAR RET = GETVAL();
的console.log(RET);

但就是不连贯......假设 doSomethingAsync()返回一个承诺,而关键字的await将从承诺返回值,而不是承诺itsef,然后我GETVAL功能的的返回值,而不是一个隐含的承诺。

那么究竟是什么回事呢?确实因async关键字标记含蓄地返回承诺的功能或我们控制它们返回什么呢?

或许,如果我们不明确地返回的东西,那么他们含蓄返回一个承诺...?

要更清楚,存在之间的差的上述和

 函数doSomethingAync(查理){
    返回新希望(函数(解析){
        的setTimeout(函数(){
            解决(查理||'亚克西');
        },100);
    })
}异步函数GETVAL(){
   VAR VAL =等待doSomethingAync(); // val不是承诺
   的console.log(VAL); //日志亚克西或什么
   返回VAL; //但是这会返回一个承诺
}VAR RET = GETVAL();
的console.log(RET); //记录一个承诺

在我的简介的行为确实与传统的return语句不一致。看来,当你明确地返回从非承诺值异步的功能,这将迫使它包装在一个承诺。
我没有与它一个很大的问题,但它无视正常的JS。


解决方案

返回值将始终是一个承诺。如果不明确地返回一个承诺,你返回值将自动被包裹在一个承诺。

 异步函数增量(NUM){
  返回NUM + 1;
}//即使你返回一个数字,该值
//自动包裹在一个承诺,所以我们称之为
//`then`它来访问返回值。
//
//日志:4
增量(3)。然后(NUM =>的console.log(NUM));

同样的事情,即使有一个等待

 功能延迟(回调){
  返回新希望(函数(解析){
    的setTimeout(函数(){
      决心(回调());
    },1000);
  });
}异步函数incrementTwice(NUM){
  常量numPlus1 =等待延迟(()=> NUM + 1);
  返回numPlus1 + 1;
}//日志:5
incrementTwice(3)。然后(NUM =>的console.log(NUM));

少辉自动展开,所以如果你做回一个承诺用于从异步函数内的值时,您将收到承诺的价值(不承诺该值的承诺)。

 功能延迟(回调){
  返回新希望(函数(解析){
    的setTimeout(函数(){
      决心(回调());
    },1000);
  });
}异步函数增量(NUM){
  //这不要紧,你是否把这里的`await`。
  返回延迟(()=> NUM + 1);
}//日志:4
增量(3)。然后(NUM =>的console.log(NUM));



  

在我的简介中的行为与传统不符确
  return语句。看来,当你明确地返回
  从一个异步函数的非承诺值,这将迫使它包装在一个
  诺言。我没有与它一个很大的问题,但它无视正常
  JS。


ES6有不返回完全相同的值作为收益功能。这些函数被称为发电机。

 功能*富(){
  返回测试;
}//记录一个对象。
的console.log(富());//日志测试。
的console.log(富()next()的值。);

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 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);

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

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