【发布时间】:2021-08-03 00:59:53
【问题描述】:
我可以减少这些仅在一个中协同工作的功能吗?如果我能做到,该怎么做?
编辑:createMedia 函数需要在 wordpress 中上传媒体文件,而 createMediaAsync 用于 await 完成上传过程,尽管这对这个问题并不重要。
const createMedia = (postImgGalleryToUpload) => {
return wp.media()
// Specify a path to the file you want to upload, or a Buffer
.file(postImgGalleryToUpload)
.create({
title: 'My awesome image',
alt_text: 'an image of something awesome',
caption: 'This is the caption text',
description: 'More explanatory information'
})
.then(function (response) {
return response.link;
});
}
const createMediaAsync = async (postImgGalleryToUpload) => {
try {
var linkImage = await createMedia(postImgGalleryToUpload);
console.log("IMMAGINE INSERITA" + linkImage);
} catch (error) {
console.log("Errore in createMediaAsync() - " + error);
}
}
在我的主文件中,我调用了异步文件:
createMediaAsync(postwp.postImgGallery1);
谢谢大家可以给我小费。
为了让问题更清楚,我想做这样的事情:
const createMedia = async (postImgGalleryToUpload) => {
return await wp.media()
// Specify a path to the file you want to upload, or a Buffer
.file(postImgGalleryToUpload)
.create({
title: 'My awesome image',
alt_text: 'an image of something awesome',
caption: 'This is the caption text',
description: 'More explanatory information'
})
.then(function (response) {
return response.link;
})
.catch(function (error) {
return error;
});
}
我知道这是错误的,实际上它根本不起作用,有没有替代方法。
谢谢
【问题讨论】:
-
目前还不清楚问题出在哪里——当然,尽管现在写的那样,你的代码无论如何都不应该工作,因为
createMedia没有返回链接。您可能想查看How do I return the response from an aynchronous call 并大致了解一些关于异步 JS 的文档/教程。 -
对不起,我不清楚,中心问题是如何在同一个函数中等待一个承诺,然后在同一个函数中等待并返回已解决的承诺。这段代码运行良好。我将更改问题以澄清问题
-
抱歉,我错过了
createMediaAsync中的await。你做的完全一样。 -
createMediaAsync不需要存在,它正在执行(几乎)它调用的函数正在执行的操作。 -
请看最后一段代码,你认为我做错了什么?
标签: javascript node.js asynchronous ecmascript-6 async-await