gpt4 book ai didi

javascript - 将 promise 代码转换为异步等待和模拟测试用例?

转载 作者:行者123 更新时间:2023-12-04 10:40:06 24 4
gpt4 key购买 nike

如何将下面嵌套的 promise 和 await 函数转换为仅使用 await 或仅使用 promises ?

const test = (url, id) => {
return new Promise((_resolve, _reject) => {
if (isValidUrl(url)) {
let storage = new Storage(Indexdb, id);
const cae = new valueExtract(url);
cae.fetch()
.then(data => {
new zip(data)
.then(obj => obj.getZip())
.then(obj => obj.getList())
.then(list => {
return new Promise(async (resolve, reject) => {
try {
let sI = storage.connection;
await Promise.all(Object.keys(list).map(async (fileName, index) => {
let blob = await new FileExtractor(list[fileName]);
await sI.setItemForce(
fileName,
new StoreObject(
fileName,
'testData',
blob
).dataObject
)
}))
_resolve(sI);
} catch (err) {
_reject(err)
}
})
})
.catch(err => _reject(err))
})
.catch(err => _reject(err))
} else {
_reject('Invalid URL')
}
})
};

我无法像我尝试的那样做同样的事情,但它从未解决
const test = async (url, id) => {
if (isValidUrl(url)) {
try {
let storage = new Storage(Indexdb, id);
const cae = new valueExtract(url);
const data = await cae.fetch();
return new ZIPExtractor(data)
.then(obj => obj.getZip())
.then(obj => obj.getList())
.then(list => {
return async (resolve, reject) => {
try {
let sI = storage.connection;
await Promise.all(Object.keys(list).map(async (fileName, index) => {
let blob = await new FileExtractor(list[fileName]);
await sI.setItemForce(
fileName,
new StoreObject(
fileName,
'testData',
blob
).dataObject
)
}))
} catch (err) {
throw new Error(err)
}
}
})
.catch(err => _reject(err))
} catch (e) {
throw new Error('Invalid URL')
}
}
};

还有我们如何为这些类型的函数编写测试用例,这样我们就不需要传入实际的网络 url 并在玩笑中模拟。

最佳答案

它应该满足,但与 async (resolve, reject) { … }return .你一开始就不应该使用它,你可以省略它:

const test = async (url, id) => {
if (!isValidUrl(url)) {
throw new Error('Invalid URL')
}
const storage = new Storage(Indexdb, id);
const cae = new valueExtract(url);
const data = await cae.fetch();
const obj = await new ZIPExtractor(data); // shudder. A constructor should never return a promise
const zip = await obj.getZip();
const list = await zip.getList();
const sI = storage.connection;
await Promise.all(Object.keys(list).map(async (fileName, index) => {
const blob = await new FileExtractor(list[fileName]);
const store = new StoreObject(fileName, 'testData', blob);
await sI.setItemForce(fileName, store.dataObject);
}));
return sI; // or something?
}

关于javascript - 将 promise 代码转换为异步等待和模拟测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59968552/

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