gpt4 book ai didi

javascript - 如何将异步 Promise 函数重构为非异步以避免反模式

转载 作者:行者123 更新时间:2023-11-28 17:08:10 27 4
gpt4 key购买 nike

我正在尝试重构使用反模式的代码,但仍然不明白如何准确地重构这样的代码:我现在有一个像这样工作的函数:

export async function submit(data) {
return new Promise(async function(resolve, reject) {
...
let list = await getList();
...
for (let i = 0; i < list.length; i++) {
let data = await getData(list[i]);
}
...
for (let i = 0; i < list.length; i++) {
let response = await uploadFile(list[i]);
}

我将此函数称为:

let response = await submit(data);

我知道新 Promise 中的异步函数有问题,但如何修复它?

export async function submit(data) {
return new Promise(async function(resolve, reject) {
let files = getFiles();

let prepareUrlsResponse = await prepareUrls(paths);
if (prepareUrlsResponse.error === true) {
resolve( { success: false });
} else {
let blobs = [];
for (let i = 0; i < prepareUrlsResponse.data.length; i++) {
let fileData = await RNFetchBlob.fs.stat(filePath);
blobs.push(fileData);
}

for (let i = 0; i < blobs.length; i++) {
let item = blobs[i];

let response = await uploadFile(
item.url,
item.blob
);

if (response && response.uploadSuccess === false) {
resolve( { success: false });
break;
}
}
}


api.post(
endpoint,
data,
response => {
if (response.ok) {
resolve( { success: true, response: response });
} else {
resolve( { success: false });
}
}
);
});
}

最佳答案

完全放弃这条线。您的 submit 已经是一个 async 函数,您可以直接在其中使用 await 。无需围绕整个事情创建一个新的 Promise,您只需要 promisfy api.post 调用。您应该将其分解为一个返回 Promise 的单独函数,并像在您调用的其他函数上一样对其使用 await

function postData(url, data) {
return new Promise(function(resolve, reject) {
// ^^^^^^^^ no `async` here!
api.post(url, data, resolve);
});
}

export async function submit(data) {
let files = getFiles();
let prepareUrlsResponse = await prepareUrls(paths);
if (prepareUrlsResponse.error === true) {
return { success: false };
} else {
let blobs = [];
for (let i = 0; i < prepareUrlsResponse.data.length; i++) {
let fileData = await RNFetchBlob.fs.stat(filePath);
blobs.push(fileData);
}

for (let i = 0; i < blobs.length; i++) {
let item = blobs[i];
let response = await uploadFile(
item.url,
item.blob
);

if (response && response.uploadSuccess === false) {
return { success: false };
}
}
}

const response = await postData(endpoint, data);
if (response.ok) {
return { success: true, response: response });
} else {
return { success: false };
}
}

您当然可以内联 postData 调用并使用 const response = wait new Promise(...);,但您应该只包装回调部分而不是整个回调逻辑。

关于javascript - 如何将异步 Promise 函数重构为非异步以避免反模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55209497/

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