我试图在 JavaScript 中创建一个构造函数,这个构造函数应该是异步的,因为我使用 Phantom JS 模块来抓取数据,所以这就是为什么我必须使用异步函数通过 Phantom JS 和 Node JS 来抓取数据。
下面是我的代码,
const phantom = require('phantom');
async function InitScrap() {
var MAIN_URL = "https://www.google.com/",
//Phantom JS Variables
instance = await phantom.create(),
page = await instance.createPage();
// Load the Basic Page First
this.loadPage = async function() {
console.log("Loading Please wait...");
var status = await page.open(MAIN_URL);
if (status == "success") {
page.render("new.png");
console.log("Site has been loaded");
}
}
}
var s = new InitScrap();
s.loadPage()
// module.exports = InitScrap();Run Code Online (Sandbox Code Playgroud)
但是当我运行这段代码时,它说,
InitScrap() …
我正在定义一个实例化几个依赖于以前模块的模块的类.模块本身在准备好之前可能需要异步操作(即建立一个mysql连接),所以我为每个构造函数提供了一个在模块准备好后调用的回调.但是,当实例化立即准备好的类时,我遇到了一个问题:
var async = require('async');
var child = function(parent, cb) {
var self = this;
this.ready = false;
this.isReady = function() {
return self.ready;
}
/* This does not work, throws error below stating c1.isReady is undefined*/
cb(null, true);
/* This works */
setTimeout(function() {
self.ready = true;
cb(null, true);
}, 0);
}
var Parent = function(cb) {
var self = this;
async.series([
function(callback){
self.c1 = new child(self, callback);
},
function(callback){
self.c2 = new child(self, callback);
}
],
function(err, results){ …Run Code Online (Sandbox Code Playgroud) 关于承诺的另一个问题.我有这种情况:
Service.prototype.parse = function (data) {
var deferred = $.Deferred();
var arr = [];
for (var i = 0; i < data.length; i++) {
var details = new Details();
$.when(details).then(function (data) {
arr.push(data);
deferred.resolve(arr);
});
}
return deferred.promise;
};
Run Code Online (Sandbox Code Playgroud)
代码中的其他地方:
...
$.when(parse()).then(function (resp) {
//...
});
Run Code Online (Sandbox Code Playgroud)
承诺在某些时候得到解决,但最初resp的长度为1.
如何等待parse()解决所有问题并返回数组?
假设我有以下数据spanish.json:
[
{"word": "casa", "translation": "house"},
{"word": "coche", "translation": "car"},
{"word": "calle", "translation": "street"}
]
Run Code Online (Sandbox Code Playgroud)
我有一个Dictionary类来加载它并添加一个搜索方法:
// Dictionary.js
class Dictionary {
constructor(url){
this.url = url;
this.entries = []; // we’ll fill this with a dictionary
this.initialize();
}
initialize(){
fetch(this.url)
.then(response => response.json())
.then(entries => this.entries = entries)
}
find(query){
return this.entries.filter(entry =>
entry.word == query)[0].translation
}
}
Run Code Online (Sandbox Code Playgroud)
我可以实例化它,并使用它通过这个小单页应用程序来查找“ calle”:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>spanish dictionary</title>
</head>
<body>
<p><input placeholder="Search for a Spanish word" type="">
<p><output></output> …Run Code Online (Sandbox Code Playgroud) 嘿,我对函数的原型和固有性有疑问。您能否解释一下如何从构造函数返回arr并将此arr添加到原型中?
var example = new Constructor()
function Constructor(){
Service.getService().then(function(data){
this.arr = data.data.array;
return this.arr
})
}
Constructor.prototype.getArray = function(){
console.log(this.arr)
})
example.getArray();
Run Code Online (Sandbox Code Playgroud)
并且在getArraythis.arr中是未定义的。Service and getService()有角度的工厂以及前端和后端之间的连接
关键字await使JavaScript等待该承诺完成并返回其结果。
我注意到它可能对await一个功能
var neonlight = await neon();
Run Code Online (Sandbox Code Playgroud)
有可能await上课吗?
例
var neonlight = await new Neon(neon_gas);
Run Code Online (Sandbox Code Playgroud) 我想知道我应该采取什么样的方法来使这段代码按照预期的方式运行.API调用是异步的 - 因此构造函数在加载数据之前返回.
addSongById: function (songId) {
var song = new Song(songId);
console.log(song);
this.addSong(song);
if (this.songCount() == 1)
this.play();
UserInterface.refresh();
SongGrid.reload();
},
function Song(songId) {
$.getJSON('http://gdata.youtube.com/feeds/api/videos/' + songId + '?v=2&alt=json-in-script&callback=?', function (data) {
this.id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); });
this.songId = songId;
this.url = "http://youtu.be/" + songId;
this.name = data.entry.title.$t;
});
}
Run Code Online (Sandbox Code Playgroud)
是否有可能强制构造函数不能过早返回?理想情况下,我不必将任意数量的参数传递给Song构造函数,并将仅与Song相关的信息带到其范围之外.
我想从我的请求“instance.web.Model”获取结果,然后调用 this.super()。问题是“instance.web.Model”是异步的,所以在我的例子中, super() 将在请求完成之前被调用。
MyObject.extend({
init: function(parent, data){
var newData = instance.web.Model('advanced.search')
.call('check_duplication', [data]).done(function (name) {
// do stuff
return name
});
data = newData;
this._super.apply(this, arguments);
// super is called before my request is done so the new data are not sent to super.
}
});
Run Code Online (Sandbox Code Playgroud)
你知道如何度过这个难关吗?为了将 newData 而不是 data 作为参数传递给超级对象。
PS:我试图将其封装在 self 中: var self = this; 但它不起作用,因为我扩展的父对象似乎继续运行而无需等待。所以我得到了像“self.super(...不是一个函数”这样的错误。
MyObject.extend({
init: function(parent, data){
var self = this;
var newData = instance.web.Model('advanced.search')
.call('check_duplication', [data]).done(function (name) {
// do stuff
var …Run Code Online (Sandbox Code Playgroud) 例:
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函数来正常工作
嗨,我试图调用异步函数makeRemoteExecutableSchema,它返回promise.
async function run() {
const schema = await makeRemoteExecutableSchema(
createApolloFetch({
uri: "https://5rrx10z19.lp.gql.zone/graphql"
})
);
}
Run Code Online (Sandbox Code Playgroud)
我在构造函数中调用此函数.
class HelloWorld {
constructor() {
try {
run();
} catch (e) {
console.log(e, e.message, e.stack);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误.有谁知道如何解决这个问题?
(node:19168) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'getQueryType' of undefined
(node:19168) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Run Code Online (Sandbox Code Playgroud) 如何让该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 新手,我需要一些帮助来了解应如何使用 promise(使用 bluebird)。下面是我的代码,我希望构造函数在解析属性后初始化一个属性。
var getCookie = function(object, someParams) {
return connect(someParams)
.then(function(response){
self.cookie = response.cookie;//this should be done as part of object initialization.
done();
});
}
var app = function(){
var self = this;
getCookie(self);
//how to make sure that return happens after promise is resolved?
return self;
}
Run Code Online (Sandbox Code Playgroud) javascript ×12
node.js ×4
promise ×4
async-await ×2
asynchronous ×2
ecmascript-6 ×2
jquery ×2
ajax ×1
async.js ×1
callback ×1
class ×1
constructor ×1
es6-class ×1
es6-promise ×1
fetch-api ×1
odoo ×1
oop ×1
phantomjs ×1
prototype ×1