gpt4 book ai didi

javascript - 新的 Promise() 与 (async () => {})()

转载 作者:行者123 更新时间:2023-12-01 16:28:16 24 4
gpt4 key购买 nike

区 block 1:

const promise = new Promise((resolve) => {
setTimeout(resolve, 100);
});

区 block 2:
const promise = (async () => {
await new Promise(resolve => {
setTimeout(resolve, 100);
});
})();

上面的两个 block 是等价的吗?有什么值得注意的区别吗?

我知道这是一个非常人为的例子,这里的第 2 block 没有太多目的。但是我遇到的一种情况是我想创建和存储对 Promise 的引用,但是 Promise 执行器函数需要使用 await 来获取一些数据。但是声明 new Promise(async (resolve) => {});被认为是反模式。在这种情况下 block 2 会更好吗?

更新:提供一个更具体的例子来说明我正在尝试做的事情:
  export async function getData(request) {
// De-dupe fetches for the same request and return existing promise.
if (map.has(JSON.stringify(request))) {
return map.get(JSON.stringify(request));
}

const thePromise = (async () => {
const [foo, bar] = Promise.all(await getFoo(), await getBar());

const theData = await getTheData(foo, bar);

return theData.some.thing ? 'a' : 'b';
})();

map.put(JSON.stringify(request), thePromise);
return thePromise;
}

最佳答案

在第二种方法中,您可以使用 trycatch block ,像这样:

const promise = (async () => {
try {
await new Promise(resolve => {
setTimeout(resolve, 100);
});
} catch(err) {
// handle error here
}
})();

关于javascript - 新的 Promise() 与 (async () => {})(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57231968/

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