kuf*_*udo 5 javascript promise async-await iife
区块 1:
const promise = new Promise((resolve) => {
setTimeout(resolve, 100);
});
Run Code Online (Sandbox Code Playgroud)
区块 2:
const promise = (async () => {
await new Promise(resolve => {
setTimeout(resolve, 100);
});
})();
Run Code Online (Sandbox Code Playgroud)
上面两个块等价吗?有什么值得注意的差异吗?
我知道这是一个精心设计的示例,这里的块 2 没有太多目的。但我遇到的情况是,我想创建并存储对 Promise 的引用,但 Promise 执行器函数需要使用 wait 来获取一些数据。但宣告new Promise(async (resolve) => {});被认为是一种反模式。在这种情况下,块 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;
}
Run Code Online (Sandbox Code Playgroud)
在第二种方法中,您可以使用tryandcatch块,如下所示:
const promise = (async () => {
try {
await new Promise(resolve => {
setTimeout(resolve, 100);
});
} catch(err) {
// handle error here
}
})();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3246 次 |
| 最近记录: |