如何在没有承诺的情况下处理异步函数? [英] How to deal with asynchronous functions without promises?
问题描述
我开始使用angularJS进行web应用程序开发,该程序带有一个promise库,但是现在我必须在没有项目的情况下进行另一个项目的开发.我将如何执行此操作而无需导入Promise库.
I started doing web-app development with angularJS which comes with a promise library but now I have to work on another project without one. How would I do this without having to import a promise library.
我已经删除了一些不相关的内容,但是基本上我需要从后端获取文件url,基于该url创建一个元素,然后返回该元素.事情是一旦进入异步函数,我就不知道如何返回以返回创建的元素.
I've removed some of the irrelevant things but basically I need to get a file url from the backend, create an element based on this url, and then return the element. The thing is once I go inside the async function, I don't know how to get back out to return the created element.
var userLogoAWS = null;
$.get("http://localhost:8080/apps/admin/file",
{
category: category,
filename: "logo.png"
},
function(data){
userLogoAWS = data;
});
img.src = userLogoAWS;
//---- Create and Combine elements ----
var element = anchor.appendChild(img);
return element;
推荐答案
在这种情况下,我将利用简单的回调模式.有很多方法可以做到这一点,但关键是要传递一个处理ajax调用成功的函数作为进行ajax调用的函数的参数.
I would take advantage of a simple callback pattern in this case. there are a lot of ways to do this but the key thing is passing a function that handles the success of the ajax call as an argument to the function that makes the ajax call.
function getLogo(createElement){
$.get("http://localhost:8080/apps/admin/file",
{
category: category,
filename: "logo.png"
},
function(data){
createElement(data)
});
}
function createElement(logo){
var img = new Image();
img.src = logo;
var element = anchor.appendChild(img);
return element; //or assign element to a global variable
}
var element = getLogo(createElement);
如果这不起作用,则JQuery具有一个Promise库,看来您正在使用jquery,所以为什么不利用它.
if this does not work, JQuery has a promise library and it seems you are using jquery, so why not take advantage of that.
这篇关于如何在没有承诺的情况下处理异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!