gpt4 book ai didi

javascript - 异步/等待隐式返回 promise ?

转载 作者:行者123 更新时间:2023-11-30 06:14:22 25 4
gpt4 key购买 nike

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

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

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

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

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

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

为了更清楚,上面和之间有区别

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

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

最佳答案

返回值永远是一个 promise 。如果您没有显式返回一个 promise ,您返回的值将自动包装在一个 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));

即使有去无回也一样! (返回 Promise { undefined })

async function increment(num) {}

即使有 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,因此如果您确实从 async 函数中返回一个值的 promise,您将收到一个对该值的 promise(不是对该值的 promise 的一个 promise) .

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 traditionalreturn statements. It appears that when you explicitly return anon-promise value from an async function, it will force wrap it in apromise. I don't have a big problem with it, but it does defy normalJS.

ES6 的函数不会返回与return 完全相同的值。这些函数称为生成器。

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

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

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

关于javascript - 异步/等待隐式返回 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57111291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com