我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo?
我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud) 我正在尝试为博客平台创建一个构造函数,它内部有许多异步操作.这些包括从目录中获取帖子,解析它们,通过模板引擎发送它们等等.
所以我的问题是,让我的构造函数返回一个promise而不是它们调用的函数的对象是不明智的new.
例如:
var engine = new Engine({path: '/path/to/posts'}).then(function (eng) {
// allow user to interact with the newly created engine object inside 'then'
engine.showPostsOnOnePage();
});
Run Code Online (Sandbox Code Playgroud)
现在,用户可能还没有提供补充Promise链链接:
var engine = new Engine({path: '/path/to/posts'});
// ERROR
// engine will not be available as an Engine object here
Run Code Online (Sandbox Code Playgroud)
这可能会造成问题,因为用户可能会感到困惑,为什么 engine 在施工后无法使用.
在构造函数中使用Promise的原因是有道理的.我希望整个博客在构建阶段后正常运行.然而,在呼叫之后,它似乎几乎无法立即访问该对象new.
我一直在争论使用的东西,engine.start().then()或者engine.init()会返回Promise.但那些看起来也很臭.
编辑:这是在Node.js项目中.
目前,我正在尝试async/await在类构造函数中使用.这样我就可以获得e-mail我正在研究的Electron项目的自定义标签.
customElements.define('e-mail', class extends HTMLElement {
async constructor() {
super()
let uid = this.getAttribute('data-uid')
let message = await grabUID(uid)
const shadowRoot = this.attachShadow({mode: 'open'})
shadowRoot.innerHTML = `
<div id="email">A random email message has appeared. ${message}</div>
`
}
})
Run Code Online (Sandbox Code Playgroud)
但是,目前该项目不起作用,出现以下错误:
Class constructor may not be an async method
Run Code Online (Sandbox Code Playgroud)
有没有办法绕过这个,以便我可以在其中使用async/await?而不是要求回调或.then()?
你有一个原型对象Foo有两个异步方法调用,bar和baz.
var bob = new Foo()
Foo.prototype.bar = function land(callback) {
setTimeout(function() {
callback()
console.log('bar');
}, 3000);
};
Foo.prototype.baz = function land(callback) {
setTimeout(function() {
callback()
console.log('baz');
}, 3000);
};
Run Code Online (Sandbox Code Playgroud)
我们想做bob.bar().baz()并按顺序记录"bar"和"baz".
如果你不能修改方法调用(包括传入你的回调函数),你如何将默认回调传递给这些方法调用?
一些想法:
用装饰器包裹"bob"(如何实现仍然模糊,可以用一个小例子)
修改构造函数以指定默认回调(如果没有分配)(未考虑是否可能)
使用生成器包装器将继续调用next方法,直到没有剩下?
我正在用aureliajs开发一个应用程序。开发过程开始了许多个月,现在,后端开发人员希望对他们的服务进行版本控制。因此,我有一个Web服务可调用以获取每个服务器端(Web api)应用程序的版本,然后针对进一步的请求,调用正确的api地址(包括其版本)。
因此,在app.js中,我请求系统元并将其存储在某处。但是某些组件在此请求完成之前已初始化。因此,他们将找不到初始化的版本并请求错误的服务器数据。
我想让app.js构造函数等到检索到此数据。例如这样的事情:
export class App {
async constructor(...) {
...
await this.initializeHttp();
...
}
initializeHttp(){
// get the system meta from server
}
}
Run Code Online (Sandbox Code Playgroud)
但是此解决方案不适用。因为构造函数不能异步。因此,在检索系统元之前,我应该如何阻止该工作?
这个问题不是这个问题的重复。在这个问题中,外部类中有一个地方等待初始化工作;尽管在我的问题中,主要的问题是等待的位置。因此,问题不仅仅在于构造函数中的异步函数,还在于在异步作业解决之前,阻止所有aurelia作业。
例:
var readBackend = function(){
var deferred = q.defer();
readData().then(function(data) {
deferred.resolve(data);
})
return deferred.promise;
}
class Test {
constructor(){
readBackend().then(function(data) {
this.importantData = data;
})
}
someFunc() {
//iterate over important data, but important data is defined
//promise didnt resolved yet
}
}
var test = new Test();
test.someFunc(); //throws exception!
Run Code Online (Sandbox Code Playgroud)
有没有办法确保,当我调用时,对象属性是由构造函数启动的someFunc?
我想到的唯一方法是创建init函数,它将返回promise,但是,每次我使用我的类时,我都会依赖init函数来正常工作
如何让该list()方法等待数据加载到构造函数中,然后再将其承诺返回给调用者?
import fetch from 'node-fetch';
class Employees {
constructor() {
if (Employees._instance) {
return Employees._instance
}
Employees._instance = this;
this.employees = [];
this.dataLoaded = false;
this.url = 'https://raw.githubusercontent.com/graphql-compose/graphql-compose-examples/master/examples/northwind/data/json/employees.json';
(async () => {
const response = await fetch(this.url);
this.employees = await response.json();
this.dataLoaded = true;
console.log(`work done: got ${this.employees.length} employees`);
})();
}
list() {
return new Promise((resolve) => {
resolve(this.employees.map(m => `${m.firstName} ${m.lastName} (${m.id})`));
});
}
}
const employees = new Employees();
(async () => {
console.log(await employees.list());
})();
Run Code Online (Sandbox Code Playgroud) javascript ×7
async-await ×3
asynchronous ×2
ecmascript-6 ×2
node.js ×2
promise ×2
ajax ×1
architecture ×1
aurelia ×1
callback ×1
class ×1
constructor ×1
es6-promise ×1
generator ×1
jquery ×1
oop ×1